import*as e from"../../core/common/common.js";import*as t from"../../core/host/host.js";import*as i from"../../core/i18n/i18n.js";import*as s from"../../core/platform/platform.js";import{assertNotNullOrUndefined as r}from"../../core/platform/platform.js";import*as a from"../../core/root/root.js";import*as o from"../../core/sdk/sdk.js";import*as n from"../../ui/components/legacy_wrapper/legacy_wrapper.js";import*as d from"../../ui/legacy/components/source_frame/source_frame.js";import*as l from"../../ui/legacy/legacy.js";import*as c from"../../ui/legacy/components/inline_editor/inline_editor.js";import*as h from"../../ui/legacy/components/utils/utils.js";import*as g from"../../ui/components/icon_button/icon_button.js";import*as u from"./components/components.js";import*as p from"../../models/bindings/bindings.js";import*as m from"../../ui/legacy/components/data_grid/data_grid.js";import*as w from"../../ui/components/chrome_link/chrome_link.js";import*as v from"./preloading/components/components.js";import*as S from"../network/network.js";import*as b from"../../ui/components/buttons/buttons.js";import*as y from"../../ui/components/helpers/helpers.js";import*as k from"../../ui/components/report_view/report_view.js";import*as f from"../../ui/legacy/components/object_ui/object_ui.js";import*as C from"../../ui/lit-html/lit-html.js";import*as T from"../../models/logs/logs.js";import*as I from"../mobile_throttling/mobile_throttling.js";import*as E from"../network/forward/forward.js";import*as M from"../../ui/legacy/components/perf_ui/perf_ui.js";import*as x from"../../models/issues_manager/issues_manager.js";import*as R from"../../ui/legacy/components/cookie_table/cookie_table.js";import*as L from"../../models/text_utils/text_utils.js";class D extends l.TreeOutline.TreeElement{resourcesPanel;constructor(e,t,i){super(t,i),this.resourcesPanel=e,l.ARIAUtils.setLabel(this.listItemElement,t)}get itemURL(){throw new Error("Unimplemented Method")}onselect(e){if(!e)return!1;const t=[];for(let e=this;e;e=e.parent){const i=e instanceof D&&e.itemURL;if(!i)break;t.push(i)}return this.resourcesPanel.setLastSelectedItemPath(t),!1}showView(e){this.resourcesPanel.showView(e)}}class P extends D{expandedSetting;categoryName;categoryLink;constructor(t,i,s,r=!1){super(t,i,!1),this.expandedSetting=e.Settings.Settings.instance().createSetting("resources"+s+"Expanded",r),this.categoryName=i,this.categoryLink=null}get itemURL(){return"category://"+this.categoryName}setLink(e){this.categoryLink=e}onselect(e){return super.onselect(e),this.resourcesPanel.showCategoryView(this.categoryName,this.categoryLink),!1}onattach(){super.onattach(),this.expandedSetting.get()&&this.expand()}onexpand(){this.expandedSetting.set(!0)}oncollapse(){this.expandedSetting.set(!1)}}const B=new CSSStyleSheet;B.replaceSync(".report-field-name{flex-basis:152px}.manifest-view-header{min-width:600px;flex-shrink:0;flex-grow:0}.manifest-container{overflow:auto}.inline-icon{margin-left:4px;margin-right:4px;vertical-align:middle}.multiline-value{white-space:normal}.inline-icon:focus-visible{outline-width:unset}\n/*# sourceURL=appManifestView.css */\n");const F={errorsAndWarnings:"Errors and warnings",installability:"Installability",identity:"Identity",presentation:"Presentation",protocolHandlers:"Protocol Handlers",icons:"Icons",windowControlsOverlay:"Window Controls Overlay",name:"Name",shortName:"Short name",computedAppId:"Computed App Id",appIdExplainer:"This is used by the browser to know whether the manifest should be updating an existing application, or whether it refers to a new web app that can be installed.",learnMore:"Learn more",appIdNote:"{PH1} {PH2} is not specified in the manifest, {PH3} is used instead. To specify an App Id that matches the current identity, set the {PH4} field to {PH5} {PH6}.",note:"Note:",copyToClipboard:"Copy to clipboard",copiedToClipboard:"Copied suggested ID {PH1} to clipboard",description:"Description",startUrl:"Start URL",themeColor:"Theme color",backgroundColor:"Background color",darkThemeColor:"Dark theme color",darkBackgroundColor:"Dark background color",orientation:"Orientation",display:"Display",newNoteUrl:"New note URL",descriptionMayBeTruncated:"Description may be truncated.",showOnlyTheMinimumSafeAreaFor:"Show only the minimum safe area for maskable icons",documentationOnMaskableIcons:"documentation on maskable icons",needHelpReadOurS:"Need help? Read {PH1}.",shortcutS:"Shortcut #{PH1}",shortcutSShouldIncludeAXPixel:"Shortcut #{PH1} should include a 96x96 pixel icon",screenshotS:"Screenshot #{PH1}",pageIsNotLoadedInTheMainFrame:"Page is not loaded in the main frame",pageIsNotServedFromASecureOrigin:"Page is not served from a secure origin",pageHasNoManifestLinkUrl:"Page has no manifest <link> `URL`",manifestCouldNotBeFetchedIsEmpty:"Manifest could not be fetched, is empty, or could not be parsed",manifestStartUrlIsNotValid:"Manifest '`start_URL`' is not valid",manifestDoesNotContainANameOr:"Manifest does not contain a '`name`' or '`short_name`' field",manifestDisplayPropertyMustBeOne:"Manifest '`display`' property must be one of '`standalone`', '`fullscreen`', or '`minimal-ui`'",manifestDoesNotContainASuitable:"Manifest does not contain a suitable icon - PNG, SVG or WebP format of at least {PH1}px is required, the '`sizes`' attribute must be set, and the '`purpose`' attribute, if set, must include '`any`'.",avoidPurposeAnyAndMaskable:"Declaring an icon with '`purpose: \"any maskable\"`' is discouraged. It is likely to look incorrect on some platforms due to too much or too little padding.",noSuppliedIconIsAtLeastSpxSquare:"No supplied icon is at least {PH1} pixels square in `PNG`, `SVG` or `WebP` format, with the purpose attribute unset or set to '`any`'.",couldNotDownloadARequiredIcon:"Could not download a required icon from the manifest",downloadedIconWasEmptyOr:"Downloaded icon was empty or corrupted",theSpecifiedApplicationPlatform:"The specified application platform is not supported on `Android`",noPlayStoreIdProvided:"No Play store ID provided",thePlayStoreAppUrlAndPlayStoreId:"The Play Store app URL and Play Store ID do not match",theAppIsAlreadyInstalled:"The app is already installed",aUrlInTheManifestContainsA:"A URL in the manifest contains a username, password, or port",pageIsLoadedInAnIncognitoWindow:"Page is loaded in an incognito window",pageDoesNotWorkOffline:"Page does not work offline",couldNotCheckServiceWorker:"Could not check `service worker` without a '`start_url`' field in the manifest",manifestSpecifies:"Manifest specifies '`prefer_related_applications`: true'",preferrelatedapplicationsIsOnly:"'`prefer_related_applications`' is only supported on `Chrome` Beta and Stable channels on `Android`.",manifestContainsDisplayoverride:"Manifest contains '`display_override`' field, and the first supported display mode must be one of '`standalone`', '`fullscreen`', or '`minimal-ui`'",pageDoesNotWorkOfflineThePage:"Page does not work offline. Starting in Chrome 93, the installability criteria are changing, and this site will not be installable. See {PH1} for more information.",imageFromS:"Image from {PH1}",screenshot:"Screenshot",icon:"Icon",sSrcIsNotSet:"{PH1} '`src`' is not set",sUrlSFailedToParse:"{PH1} URL ''{PH2}'' failed to parse",sSFailedToLoad:"{PH1} {PH2} failed to load",sSDoesNotSpecifyItsSizeInThe:"{PH1} {PH2} does not specify its size in the manifest",sSShouldSpecifyItsSizeAs:"{PH1} {PH2} should specify its size as `[width]x[height]`",sSShouldHaveSquareIcon:"Most operating systems require square icons. Please include at least one square icon in the array.",actualSizeSspxOfSSDoesNotMatch:"Actual size ({PH1}×{PH2})px of {PH3} {PH4} does not match specified size ({PH5}×{PH6}px)",actualWidthSpxOfSSDoesNotMatch:"Actual width ({PH1}px) of {PH2} {PH3} does not match specified width ({PH4}px)",actualHeightSpxOfSSDoesNotMatch:"Actual height ({PH1}px) of {PH2} {PH3} does not match specified height ({PH4}px)",sSSizeShouldBeAtLeast320:"{PH1} {PH2} size should be at least 320×320",sSSizeShouldBeAtMost3840:"{PH1} {PH2} size should be at most 3840×3840",sSWidthDoesNotComplyWithRatioRequirement:"{PH1} {PH2} width can't be more than 2.3 times as long as the height",sSHeightDoesNotComplyWithRatioRequirement:"{PH1} {PH2} height can't be more than 2.3 times as long as the width",screenshotPixelSize:'Screenshot {url} should specify a pixel size `[width]x[height]` instead of `"any"` as first size.',displayOverride:"display-override",wcoFound:"Chrome has successfully found the {PH1} value for the {PH2} field in the {PH3}.",wcoNotFound:"Define {PH1} in the manifest to use the Window Controls Overlay API and customize your app's title bar.",customizePwaTitleBar:"Customize the window controls overlay of your PWA's title bar.",wcoNeedHelpReadMore:"Need help? Read {PH1}."},V=i.i18n.registerUIStrings("panels/application/AppManifestView.ts",F),A=i.i18n.getLocalizedString.bind(void 0,V);class O extends l.Widget.VBox{emptyView;reportView;errorsSection;installabilitySection;identitySection;presentationSection;iconsSection;windowsControlsOverlaySection;protocolHandlersSection;shortcutSections;screenshotsSections;nameField;shortNameField;descriptionField;startURLField;themeColorSwatch;backgroundColorSwatch;darkThemeColorField;darkThemeColorSwatch;darkBackgroundColorField;darkBackgroundColorSwatch;orientationField;displayField;newNoteUrlField;throttler;registeredListeners;target;resourceTreeModel;serviceWorkerManager;protocolHandlersView;manifestLink;constructor(t,i,s){super(!0),this.contentElement.classList.add("manifest-container"),e.Settings.Settings.instance().moduleSetting("colorFormat").addChangeListener(this.updateManifest.bind(this,!0)),this.emptyView=t,this.emptyView.appendLink("https://web.dev/add-manifest/"),this.emptyView.show(this.contentElement),this.emptyView.hideWidget(),this.reportView=i,this.reportView.element.classList.add("manifest-view-header"),this.reportView.show(this.contentElement),this.reportView.hideWidget(),this.errorsSection=this.reportView.appendSection(A(F.errorsAndWarnings)),this.installabilitySection=this.reportView.appendSection(A(F.installability)),this.identitySection=this.reportView.appendSection(A(F.identity)),this.presentationSection=this.reportView.appendSection(A(F.presentation)),this.protocolHandlersSection=this.reportView.appendSection(A(F.protocolHandlers)),this.protocolHandlersView=new u.ProtocolHandlersView.ProtocolHandlersView,this.protocolHandlersSection.appendFieldWithCustomView(this.protocolHandlersView),this.iconsSection=this.reportView.appendSection(A(F.icons),"report-section-icons"),this.windowsControlsOverlaySection=this.reportView.appendSection(F.windowControlsOverlay),this.shortcutSections=[],this.screenshotsSections=[],this.nameField=this.identitySection.appendField(A(F.name)),this.shortNameField=this.identitySection.appendField(A(F.shortName)),this.descriptionField=this.identitySection.appendFlexedField(A(F.description)),this.startURLField=this.presentationSection.appendField(A(F.startUrl)),l.ARIAUtils.setLabel(this.startURLField,A(F.startUrl));const r=this.presentationSection.appendField(A(F.themeColor));this.themeColorSwatch=new c.ColorSwatch.ColorSwatch,r.appendChild(this.themeColorSwatch);const a=this.presentationSection.appendField(A(F.backgroundColor));this.backgroundColorSwatch=new c.ColorSwatch.ColorSwatch,a.appendChild(this.backgroundColorSwatch),this.darkThemeColorField=this.presentationSection.appendField(A(F.darkThemeColor)),this.darkThemeColorSwatch=new c.ColorSwatch.ColorSwatch,this.darkThemeColorField.appendChild(this.darkThemeColorSwatch),this.darkBackgroundColorField=this.presentationSection.appendField(A(F.darkBackgroundColor)),this.darkBackgroundColorSwatch=new c.ColorSwatch.ColorSwatch,this.darkBackgroundColorField.appendChild(this.darkBackgroundColorSwatch),this.orientationField=this.presentationSection.appendField(A(F.orientation)),this.displayField=this.presentationSection.appendField(A(F.display)),this.newNoteUrlField=this.presentationSection.appendField(A(F.newNoteUrl)),this.throttler=s,o.TargetManager.TargetManager.instance().observeTargets(this),this.registeredListeners=[]}getStaticSections(){return[this.identitySection,this.presentationSection,this.protocolHandlersSection,this.iconsSection,this.windowsControlsOverlaySection]}getManifestElement(){return this.reportView.getHeaderElement()}targetAdded(e){e===o.TargetManager.TargetManager.instance().primaryPageTarget()&&(this.target=e,this.resourceTreeModel=e.model(o.ResourceTreeModel.ResourceTreeModel),this.serviceWorkerManager=e.model(o.ServiceWorkerManager.ServiceWorkerManager),this.resourceTreeModel&&this.serviceWorkerManager&&(this.updateManifest(!0),this.registeredListeners=[this.resourceTreeModel.addEventListener(o.ResourceTreeModel.Events.DOMContentLoaded,(()=>{this.updateManifest(!0)})),this.serviceWorkerManager.addEventListener(o.ServiceWorkerManager.Events.RegistrationUpdated,(()=>{this.updateManifest(!1)}))]))}targetRemoved(t){this.target===t&&this.resourceTreeModel&&this.serviceWorkerManager&&(delete this.resourceTreeModel,delete this.serviceWorkerManager,e.EventTarget.removeEventListeners(this.registeredListeners))}async updateManifest(e){if(!this.resourceTreeModel)return;const[{url:t,data:i,errors:s},r,a]=await Promise.all([this.resourceTreeModel.fetchAppManifest(),this.resourceTreeModel.getInstallabilityErrors(),this.resourceTreeModel.getAppId()]);this.throttler.schedule((()=>this.renderManifest(t,i,s,r,a)),e)}async renderManifest(s,r,a,o,n){const d=n?.appId||null,c=n?.recommendedId||null;if(!r&&!a.length)return this.emptyView.showWidget(),this.reportView.hideWidget(),void this.contentElement.dispatchEvent(new CustomEvent("manifestDetection",{detail:!1}));this.emptyView.hideWidget(),this.reportView.showWidget(),this.contentElement.dispatchEvent(new CustomEvent("manifestDetection",{detail:!0}));const u=h.Linkifier.Linkifier.linkifyURL(s);this.manifestLink=u,u.tabIndex=0,this.reportView.setURL(u),this.errorsSection.clearContent(),this.errorsSection.element.classList.toggle("hidden",!a.length);for(const e of a){const t=l.UIUtils.createIconLabel({title:e.message,iconName:e.critical?"cross-circle-filled":"warning-filled",color:e.critical?"var(--icon-error)":"var(--icon-warning)"});this.errorsSection.appendRow().appendChild(t)}if(!r)return;65279===r.charCodeAt(0)&&(r=r.slice(1));const p=JSON.parse(r);this.nameField.textContent=_("name"),this.shortNameField.textContent=_("short_name");const m=[],w=_("description");this.descriptionField.textContent=w,w.length>324&&m.push(A(F.descriptionMayBeTruncated));const v=_("start_url");if(d&&c){const e=this.identitySection.appendField(A(F.computedAppId));l.ARIAUtils.setLabel(e,"App Id"),e.textContent=d;const s=new g.Icon.Icon;if(s.data={iconName:"help",color:"var(--icon-default)",width:"16px",height:"16px"},s.classList.add("inline-icon"),s.title=A(F.appIdExplainer),s.tabIndex=0,e.appendChild(s),e.appendChild(l.XLink.XLink.create("https://developer.chrome.com/blog/pwa-manifest-id/",A(F.learnMore))),!_("id")){const s=e.createChild("div","multiline-value"),r=document.createElement("b");r.textContent=A(F.note);const a=document.createElement("code");a.textContent="id";const o=document.createElement("code");o.textContent="id";const n=document.createElement("code");n.textContent="start_url";const d=document.createElement("code");d.textContent=c;const h=new g.IconButton.IconButton;h.title=A(F.copyToClipboard),h.data={groups:[{iconName:"copy",iconHeight:"12px",iconWidth:"12px",text:"",iconColor:"var(--icon-default-hover)"}],clickHandler:()=>{l.ARIAUtils.alert(A(F.copiedToClipboard,{PH1:c})),t.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(c)},compact:!0,accessibleName:A(F.copyToClipboard)},s.appendChild(i.i18n.getFormatLocalizedString(V,F.appIdNote,{PH1:r,PH2:a,PH3:n,PH4:o,PH5:d,PH6:h}))}}else this.identitySection.removeField(A(F.computedAppId));if(this.startURLField.removeChildren(),v){const t=e.ParsedURL.ParsedURL.completeURL(s,v);if(t){const e=h.Linkifier.Linkifier.linkifyURL(t,{text:v});e.tabIndex=0,this.startURLField.appendChild(e)}}this.themeColorSwatch.classList.toggle("hidden",!_("theme_color"));const S=e.Color.parse(_("theme_color")||"white")||e.Color.parse("white");S&&this.themeColorSwatch.renderColor(S,!0),this.backgroundColorSwatch.classList.toggle("hidden",!_("background_color"));const b=e.Color.parse(_("background_color")||"white")||e.Color.parse("white");b&&this.backgroundColorSwatch.renderColor(b,!0);const y=((p.user_preferences||{}).color_scheme||{}).dark||{},k=y.theme_color,f="string"==typeof k;if(this.darkThemeColorField.parentElement?.classList.toggle("hidden",!f),f){const t=e.Color.parse(k);t&&this.darkThemeColorSwatch.renderColor(t,!0)}const C=y.background_color,T="string"==typeof C;if(this.darkBackgroundColorField.parentElement?.classList.toggle("hidden",!T),T){const t=e.Color.parse(C);t&&this.darkBackgroundColorSwatch.renderColor(t,!0)}this.orientationField.textContent=_("orientation");const I=_("display");this.displayField.textContent=I;const E=(p.note_taking||{}).new_note_url,M="string"==typeof E;if(this.newNoteUrlField.parentElement?.classList.toggle("hidden",!M),this.newNoteUrlField.removeChildren(),M){const t=e.ParsedURL.ParsedURL.completeURL(s,E),i=h.Linkifier.Linkifier.linkifyURL(t,{text:E});i.tabIndex=0,this.newNoteUrlField.appendChild(i)}const x=p.protocol_handlers||[];this.protocolHandlersView.data={protocolHandlers:x,manifestLink:s};const R=p.icons||[];this.iconsSection.clearContent();const L=p.shortcuts||[];for(const e of this.shortcutSections)e.detach(!0);const D=p.screenshots||[];for(const e of this.screenshotsSections)e.detach(!0);const P=[],B=l.UIUtils.CheckboxLabel.create(A(F.showOnlyTheMinimumSafeAreaFor));B.classList.add("mask-checkbox"),B.addEventListener("click",(()=>{this.iconsSection.setIconMasked(B.checkboxElement.checked)})),this.iconsSection.appendRow().appendChild(B);const O=l.XLink.XLink.create("https://web.dev/maskable-icon/",A(F.documentationOnMaskableIcons));this.iconsSection.appendRow().appendChild(i.i18n.getFormatLocalizedString(V,F.needHelpReadOurS,{PH1:O}));let W=!1;for(const e of R){const t=await this.appendImageResourceToSection(s,e,this.iconsSection,!1);P.push(...t.imageResourceErrors),W=t.squareSizedIconAvailable||W}W||P.push(A(F.sSShouldHaveSquareIcon));let U=1;for(const t of L){const i=this.reportView.appendSection(A(F.shortcutS,{PH1:U}));this.shortcutSections.push(i),i.appendFlexedField("Name",t.name),t.short_name&&i.appendFlexedField("Short name",t.short_name),t.description&&i.appendFlexedField("Description",t.description);const r=i.appendFlexedField("URL"),a=e.ParsedURL.ParsedURL.completeURL(s,t.url),o=h.Linkifier.Linkifier.linkifyURL(a,{text:t.url});o.tabIndex=0,r.appendChild(o);const n=t.icons||[];let d=!1;for(const e of n){const{imageResourceErrors:t}=await this.appendImageResourceToSection(s,e,i,!1);if(P.push(...t),!d&&e.sizes){const t=e.sizes.match(/^(\d+)x(\d+)$/);t&&t[1]>=96&&t[2]>=96&&(d=!0)}}d||P.push(A(F.shortcutSShouldIncludeAXPixel,{PH1:U})),U++}let N=1;for(const e of D){const t=this.reportView.appendSection(A(F.screenshotS,{PH1:N}));this.screenshotsSections.push(t);const{imageResourceErrors:i}=await this.appendImageResourceToSection(s,e,t,!0);P.push(...i),N++}this.installabilitySection.clearContent(),this.installabilitySection.element.classList.toggle("hidden",!o.length);const H=this.getInstallabilityErrorMessages(o);for(const e of H){const t=l.UIUtils.createIconLabel({title:e,iconName:"warning-filled",color:"var(--icon-warning)"});this.installabilitySection.appendRow().appendChild(t)}this.errorsSection.element.classList.toggle("hidden",!a.length&&!P.length&&!m.length);for(const e of m){const t=l.UIUtils.createIconLabel({title:e,iconName:"warning-filled",color:"var(--icon-warning)"});this.errorsSection.appendRow().appendChild(t)}for(const e of P){const t=l.UIUtils.createIconLabel({title:e,iconName:"warning-filled",color:"var(--icon-warning)"});this.errorsSection.appendRow().appendChild(t)}function _(e){const t=p[e];return"string"!=typeof t?"":t}this.windowsControlsOverlaySection.clearContent();const G=(p.display_override||[]).includes("window-controls-overlay"),q=l.XLink.XLink.create("https://developer.mozilla.org/en-US/docs/Web/Manifest/display_override",A(F.displayOverride)),K=document.createElement("code");K.appendChild(q);const j=this.windowsControlsOverlaySection.appendRow();if(G){const e=new g.Icon.Icon;e.data={iconName:"check-circle",color:"var(--icon-checkmark-green)",width:"16px",height:"16px"},e.classList.add("inline-icon"),e.tabIndex=0,j.appendChild(e);const t=document.createElement("code");t.classList.add("wco"),t.textContent="window-controls-overlay",j.appendChild(i.i18n.getFormatLocalizedString(V,F.wcoFound,{PH1:t,PH2:K,PH3:this.manifestLink}))}else{const e=new g.Icon.Icon;e.data={iconName:"info",color:"var(--icon-default)",width:"16px",height:"16px"},e.classList.add("inline-icon"),e.tabIndex=0,j.appendChild(e),j.appendChild(i.i18n.getFormatLocalizedString(V,F.wcoNotFound,{PH1:K}))}const z=l.XLink.XLink.create("https://learn.microsoft.com/en-us/microsoft-edge/progressive-web-apps-chromium/how-to/window-controls-overlay",A(F.customizePwaTitleBar));this.windowsControlsOverlaySection.appendRow().appendChild(i.i18n.getFormatLocalizedString(V,F.wcoNeedHelpReadMore,{PH1:z}))}getInstallabilityErrorMessages(e){const t=[];for(const i of e){let e;switch(i.errorId){case"not-in-main-frame":e=A(F.pageIsNotLoadedInTheMainFrame);break;case"not-from-secure-origin":e=A(F.pageIsNotServedFromASecureOrigin);break;case"no-manifest":e=A(F.pageHasNoManifestLinkUrl);break;case"manifest-empty":e=A(F.manifestCouldNotBeFetchedIsEmpty);break;case"start-url-not-valid":e=A(F.manifestStartUrlIsNotValid);break;case"manifest-missing-name-or-short-name":e=A(F.manifestDoesNotContainANameOr);break;case"manifest-display-not-supported":e=A(F.manifestDisplayPropertyMustBeOne);break;case"manifest-missing-suitable-icon":if(1!==i.errorArguments.length||"minimum-icon-size-in-pixels"!==i.errorArguments[0].name){console.error("Installability error does not have the correct errorArguments");break}e=A(F.manifestDoesNotContainASuitable,{PH1:i.errorArguments[0].value});break;case"no-acceptable-icon":if(1!==i.errorArguments.length||"minimum-icon-size-in-pixels"!==i.errorArguments[0].name){console.error("Installability error does not have the correct errorArguments");break}e=A(F.noSuppliedIconIsAtLeastSpxSquare,{PH1:i.errorArguments[0].value});break;case"cannot-download-icon":e=A(F.couldNotDownloadARequiredIcon);break;case"no-icon-available":e=A(F.downloadedIconWasEmptyOr);break;case"platform-not-supported-on-android":e=A(F.theSpecifiedApplicationPlatform);break;case"no-id-specified":e=A(F.noPlayStoreIdProvided);break;case"ids-do-not-match":e=A(F.thePlayStoreAppUrlAndPlayStoreId);break;case"already-installed":e=A(F.theAppIsAlreadyInstalled);break;case"url-not-supported-for-webapk":e=A(F.aUrlInTheManifestContainsA);break;case"in-incognito":e=A(F.pageIsLoadedInAnIncognitoWindow);break;case"not-offline-capable":e=A(F.pageDoesNotWorkOffline);break;case"no-url-for-service-worker":e=A(F.couldNotCheckServiceWorker);break;case"prefer-related-applications":e=A(F.manifestSpecifies);break;case"prefer-related-applications-only-beta-stable":e=A(F.preferrelatedapplicationsIsOnly);break;case"manifest-display-override-not-supported":e=A(F.manifestContainsDisplayoverride);break;case"warn-not-offline-capable":e=A(F.pageDoesNotWorkOfflineThePage,{PH1:"https://developer.chrome.com/blog/improved-pwa-offline-detection/"});break;default:console.error(`Installability error id '${i.errorId}' is not recognized`)}e&&t.push(e)}return t}async loadImage(e){const t=document.createElement("div");t.classList.add("image-wrapper");const i=document.createElement("img"),s=new Promise(((e,t)=>{i.onload=e,i.onerror=t}));i.src=e,i.alt=A(F.imageFromS,{PH1:e}),t.appendChild(i);try{return await s,{wrapper:t,image:i}}catch(e){}return null}parseSizes(e,t,i,s){const r=e.split(/\s+/),a=[];for(const e of r){if("any"===e){a.find((e=>"any"in e))||a.push({any:"any",formatted:"any"});continue}const r=e.match(/^(?<width>\d+)[xX](?<height>\d+)$/);if(r){const e=parseInt(r.groups?.width||"",10),t=parseInt(r.groups?.height||"",10),i=`${e}×${t}px`;a.push({width:e,height:t,formatted:i})}else s.push(A(F.sSShouldSpecifyItsSizeAs,{PH1:t,PH2:i}))}return a}checkSizeProblem(e,t,i,s,r){if("any"in e)return{hasSquareSize:i.naturalWidth===i.naturalHeight};const a=e.width===e.height;return i.naturalWidth!==e.width&&i.naturalHeight!==e.height?{error:A(F.actualSizeSspxOfSSDoesNotMatch,{PH1:i.naturalWidth,PH2:i.naturalHeight,PH3:s,PH4:r,PH5:e.width,PH6:e.height}),hasSquareSize:a}:i.naturalWidth!==e.width?{error:A(F.actualWidthSpxOfSSDoesNotMatch,{PH1:i.naturalWidth,PH2:s,PH3:r,PH4:e.width}),hasSquareSize:a}:i.naturalHeight!==e.height?{error:A(F.actualHeightSpxOfSSDoesNotMatch,{PH1:i.naturalHeight,PH2:s,PH3:r,PH4:e.height}),hasSquareSize:a}:{hasSquareSize:a}}async appendImageResourceToSection(t,i,s,r){const a=[],o=A(r?F.screenshot:F.icon);if(!i.src)return a.push(A(F.sSrcIsNotSet,{PH1:o})),{imageResourceErrors:a};const n=e.ParsedURL.ParsedURL.completeURL(t,i.src);if(!n)return a.push(A(F.sUrlSFailedToParse,{PH1:o,PH2:i.src})),{imageResourceErrors:a};const d=await this.loadImage(n);if(!d)return a.push(A(F.sSFailedToLoad,{PH1:o,PH2:n})),{imageResourceErrors:a};const{wrapper:l,image:c}=d,h=this.parseSizes(i.sizes,o,n,a),g=h.map((e=>e.formatted)).join(" ")+"\n"+(i.type||""),u=s.appendFlexedField(g);let p=!1;if(i.sizes){r&&h.length>0&&"any"in h[0]&&a.push(A(F.screenshotPixelSize,{url:n}));for(const e of h){const{error:t,hasSquareSize:s}=this.checkSizeProblem(e,i.type,c,o,n);if(p=p||s,t)a.push(t);else if(r){const t="any"in e?c.naturalWidth:e.width,i="any"in e?c.naturalHeight:e.height;t<320||i<320?a.push(A(F.sSSizeShouldBeAtLeast320,{PH1:o,PH2:n})):t>3840||i>3840?a.push(A(F.sSSizeShouldBeAtMost3840,{PH1:o,PH2:n})):t>2.3*i?a.push(A(F.sSWidthDoesNotComplyWithRatioRequirement,{PH1:o,PH2:n})):i>2.3*t&&a.push(A(F.sSHeightDoesNotComplyWithRatioRequirement,{PH1:o,PH2:n}))}}}else a.push(A(F.sSDoesNotSpecifyItsSizeInThe,{PH1:o,PH2:n}));c.width=c.naturalWidth;const m="string"==typeof i.purpose?i.purpose.toLowerCase():"";return m.includes("any")&&m.includes("maskable")&&a.push(A(F.avoidPurposeAnyAndMaskable)),u.appendChild(l),{imageResourceErrors:a,squareSizedIconAvailable:p}}wasShown(){super.wasShown(),this.reportView.registerCSSFiles([B]),this.registerCSSFiles([B])}}var W=Object.freeze({__proto__:null,AppManifestView:O});const U={backForwardCache:"Back/forward cache"},N=i.i18n.registerUIStrings("panels/application/BackForwardCacheTreeElement.ts",U),H=i.i18n.getLocalizedString.bind(void 0,N);class _ extends D{view;constructor(e){super(e,H(U.backForwardCache),!1);const t=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([t])}get itemURL(){return"bfcache://"}onselect(e){return super.onselect(e),this.view||(this.view=n.LegacyWrapper.legacyWrapper(l.Widget.Widget,new u.BackForwardCacheView.BackForwardCacheView)),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.back_forward_cache]),!1}}class G extends o.SDKModel.SDKModel{backgroundServiceAgent;events;constructor(e){super(e),this.backgroundServiceAgent=e.backgroundServiceAgent(),e.registerBackgroundServiceDispatcher(this),this.events=new Map}enable(e){this.events.set(e,[]),this.backgroundServiceAgent.invoke_startObserving({service:e})}setRecording(e,t){this.backgroundServiceAgent.invoke_setRecording({shouldRecord:e,service:t})}clearEvents(e){this.events.set(e,[]),this.backgroundServiceAgent.invoke_clearEvents({service:e})}getEvents(e){return this.events.get(e)||[]}recordingStateChanged({isRecording:e,service:t}){this.dispatchEventToListeners(q.RecordingStateChanged,{isRecording:e,serviceName:t})}backgroundServiceEventReceived({backgroundServiceEvent:e}){this.events.get(e.service).push(e),this.dispatchEventToListeners(q.BackgroundServiceEventReceived,e)}}var q;o.SDKModel.SDKModel.register(G,{capabilities:o.Target.Capability.Browser,autostart:!1}),function(e){e.RecordingStateChanged="RecordingStateChanged",e.BackgroundServiceEventReceived="BackgroundServiceEventReceived"}(q||(q={}));var K=Object.freeze({__proto__:null,BackgroundServiceModel:G,get Events(){return q}});const j=new CSSStyleSheet;j.replaceSync(".empty-bold-text{display:block;font-size:1.5em;margin:0.83em 0;font-weight:bold}.empty-view{color:var(--color-text-secondary);padding:30px;text-align:center;min-width:70px}.empty-view-scroller{justify-content:center;overflow:auto}.empty-view p{white-space:initial;line-height:18px;max-width:300px;flex-shrink:0}\n/*# sourceURL=emptyWidget.css */\n");const z=new CSSStyleSheet;z.replaceSync(".background-service-toolbar{background-color:var(--color-background-elevation-1);border-bottom:var(--legacy-divider-border)}.data-grid{flex:auto;border:none}.background-service-preview{position:absolute;background-color:var(--color-background);justify-content:center;align-items:center;overflow:auto;font-size:13px;color:var(--color-text-secondary)}.background-service-preview > div{max-width:450px;margin:10px;text-align:center}.background-service-preview > div > p{flex:none;white-space:pre-line}.background-service-shortcut{color:var(--color-text-secondary)}.background-service-metadata{padding-left:5px;padding-top:10px}.background-service-metadata-entry{padding-left:10px;padding-bottom:5px}.background-service-metadata-name{color:var(--color-text-secondary);display:inline-block;margin-right:0.25em;font-weight:bold}.background-service-metadata-value{display:inline;margin-right:1em;white-space:pre-wrap;word-break:break-all;user-select:text}.background-service-empty-value{color:var(--color-text-disabled);font-style:italic}.background-service-record-inline-button{margin-bottom:6px}\n/*# sourceURL=backgroundServiceView.css */\n");const Q={backgroundFetch:"Background Fetch",backgroundSync:"Background Sync",pushMessaging:"Push Messaging",notifications:"Notifications",paymentHandler:"Payment Handler",periodicBackgroundSync:"Periodic Background Sync",clear:"Clear",saveEvents:"Save events",showEventsFromOtherDomains:"Show events from other domains",showEventsForOtherStorageKeys:"Show events from other storage partitions",stopRecordingEvents:"Stop recording events",startRecordingEvents:"Start recording events",timestamp:"Timestamp",event:"Event",origin:"Origin",storageKey:"Storage Key",swScope:"Service Worker Scope",instanceId:"Instance ID",backgroundServices:"Background Services",learnMore:"Learn more",selectAnEntryToViewMetadata:"Select an entry to view metadata",recordingSActivity:"Recording {PH1} activity...",devtoolsWillRecordAllSActivity:"DevTools will record all {PH1} activity for up to 3 days, even when closed.",clickTheRecordButtonSOrHitSTo:"Click the record button {PH1} or hit {PH2} to start recording.",empty:"empty",noMetadataForThisEvent:"No metadata for this event"},$=i.i18n.registerUIStrings("panels/application/BackgroundServiceView.ts",Q),J=i.i18n.getLocalizedString.bind(void 0,$);class X extends l.Widget.VBox{serviceName;model;serviceWorkerManager;securityOriginManager;storageKeyManager;recordAction;recordButton;originCheckbox;storageKeyCheckbox;saveButton;toolbar;splitWidget;dataGrid;previewPanel;selectedEventNode;preview;static getUIString(e){switch(e){case"backgroundFetch":return J(Q.backgroundFetch);case"backgroundSync":return J(Q.backgroundSync);case"pushMessaging":return J(Q.pushMessaging);case"notifications":return J(Q.notifications);case"paymentHandler":return J(Q.paymentHandler);case"periodicBackgroundSync":return J(Q.periodicBackgroundSync);default:return""}}constructor(e,t){if(super(!0),this.serviceName=e,this.model=t,this.model.addEventListener(q.RecordingStateChanged,this.onRecordingStateChanged,this),this.model.addEventListener(q.BackgroundServiceEventReceived,this.onEventReceived,this),this.model.enable(this.serviceName),this.serviceWorkerManager=this.model.target().model(o.ServiceWorkerManager.ServiceWorkerManager),this.securityOriginManager=this.model.target().model(o.SecurityOriginManager.SecurityOriginManager),!this.securityOriginManager)throw new Error("SecurityOriginManager instance is missing");if(this.securityOriginManager.addEventListener(o.SecurityOriginManager.Events.MainSecurityOriginChanged,(()=>this.onOriginChanged())),this.storageKeyManager=this.model.target().model(o.StorageKeyManager.StorageKeyManager),!this.storageKeyManager)throw new Error("StorageKeyManager instance is missing");this.storageKeyManager.addEventListener(o.StorageKeyManager.Events.MainStorageKeyChanged,(()=>this.onStorageKeyChanged())),this.recordAction=l.ActionRegistry.ActionRegistry.instance().action("background-service.toggle-recording"),this.toolbar=new l.Toolbar.Toolbar("background-service-toolbar",this.contentElement),this.setupToolbar(),this.splitWidget=new l.SplitWidget.SplitWidget(!1,!0),this.splitWidget.show(this.contentElement),this.dataGrid=this.createDataGrid(),this.previewPanel=new l.Widget.VBox,this.selectedEventNode=null,this.preview=null,this.splitWidget.setMainWidget(this.dataGrid.asWidget()),this.splitWidget.setSidebarWidget(this.previewPanel),this.showPreview(null)}getDataGrid(){return this.dataGrid}async setupToolbar(){this.recordButton=l.Toolbar.Toolbar.createActionButton(this.recordAction),this.toolbar.appendToolbarItem(this.recordButton);const e=new l.Toolbar.ToolbarButton(J(Q.clear),"clear");e.addEventListener(l.Toolbar.ToolbarButton.Events.Click,(()=>this.clearEvents())),this.toolbar.appendToolbarItem(e),this.toolbar.appendSeparator(),this.saveButton=new l.Toolbar.ToolbarButton(J(Q.saveEvents),"download"),this.saveButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,(e=>{this.saveToFile()})),this.saveButton.setEnabled(!1),this.toolbar.appendToolbarItem(this.saveButton),this.toolbar.appendSeparator(),this.originCheckbox=new l.Toolbar.ToolbarCheckbox(J(Q.showEventsFromOtherDomains),J(Q.showEventsFromOtherDomains),(()=>this.refreshView())),this.toolbar.appendToolbarItem(this.originCheckbox),this.storageKeyCheckbox=new l.Toolbar.ToolbarCheckbox(J(Q.showEventsForOtherStorageKeys),J(Q.showEventsForOtherStorageKeys),(()=>this.refreshView())),this.toolbar.appendToolbarItem(this.storageKeyCheckbox)}refreshView(){this.clearView();const e=this.model.getEvents(this.serviceName).filter((e=>this.acceptEvent(e)));for(const t of e)this.addEvent(t)}clearView(){this.selectedEventNode=null,this.dataGrid.rootNode().removeChildren(),this.saveButton.setEnabled(!1),this.showPreview(null)}toggleRecording(){this.model.setRecording(!this.recordButton.toggled(),this.serviceName)}clearEvents(){this.model.clearEvents(this.serviceName),this.clearView()}onRecordingStateChanged({data:e}){e.serviceName===this.serviceName&&e.isRecording!==this.recordButton.toggled()&&(this.recordButton.setToggled(e.isRecording),this.updateRecordButtonTooltip(),this.showPreview(this.selectedEventNode))}updateRecordButtonTooltip(){const e=this.recordButton.toggled()?J(Q.stopRecordingEvents):J(Q.startRecordingEvents);this.recordButton.setTitle(e,"background-service.toggle-recording")}onEventReceived({data:e}){this.acceptEvent(e)&&this.addEvent(e)}onOriginChanged(){this.originCheckbox.checked()||this.refreshView()}onStorageKeyChanged(){this.storageKeyCheckbox.checked()||this.refreshView()}addEvent(e){const t=this.createEventData(e),i=new Y(t,e.eventMetadata);this.dataGrid.rootNode().appendChild(i),1===this.dataGrid.rootNode().children.length&&(this.saveButton.setEnabled(!0),this.showPreview(this.selectedEventNode))}createDataGrid(){const e=[{id:"id",title:"#",weight:1},{id:"timestamp",title:J(Q.timestamp),weight:7},{id:"eventName",title:J(Q.event),weight:8},{id:"origin",title:J(Q.origin),weight:8},{id:"storageKey",title:J(Q.storageKey),weight:8},{id:"swScope",title:J(Q.swScope),weight:4},{id:"instanceId",title:J(Q.instanceId),weight:8}],t=new m.DataGrid.DataGridImpl({displayName:J(Q.backgroundServices),columns:e,editCallback:void 0,refreshCallback:void 0,deleteCallback:void 0});return t.setStriped(!0),t.addEventListener(m.DataGrid.Events.SelectedNode,(e=>this.showPreview(e.data))),t}createEventData(e){let t="";const i=this.serviceWorkerManager?this.serviceWorkerManager.registrations().get(e.serviceWorkerRegistrationId):void 0;return i&&(t=i.scopeURL.substr(i.securityOrigin.length)),{id:this.dataGrid.rootNode().children.length+1,timestamp:l.UIUtils.formatTimestamp(1e3*e.timestamp,!0),origin:e.origin,storageKey:e.storageKey,swScope:t,eventName:e.eventName,instanceId:e.instanceId}}acceptEvent(e){if(e.service!==this.serviceName)return!1;if(this.originCheckbox.checked()||this.storageKeyCheckbox.checked())return!0;const t=e.origin.substr(0,e.origin.length-1),i=e.storageKey;return this.securityOriginManager.securityOrigins().includes(t)||this.storageKeyManager.storageKeys().includes(i)}createLearnMoreLink(){let e="https://developer.chrome.com/docs/devtools/javascript/background-services/?utm_source=devtools";switch(this.serviceName){case"backgroundFetch":e+="#fetch";break;case"backgroundSync":e+="#sync";break;case"pushMessaging":e+="#push";break;case"notifications":e+="#notifications"}return l.XLink.XLink.create(e,J(Q.learnMore))}showPreview(e){if(this.selectedEventNode&&this.selectedEventNode===e)return;if(this.selectedEventNode=e,this.preview&&this.preview.detach(),this.selectedEventNode)return this.preview=this.selectedEventNode.createPreview(),void this.preview.show(this.previewPanel.contentElement);this.preview=new l.Widget.VBox,this.preview.contentElement.classList.add("background-service-preview","fill");const t=this.preview.contentElement.createChild("div");if(this.dataGrid.rootNode().children.length)t.createChild("p").textContent=J(Q.selectAnEntryToViewMetadata);else if(this.recordButton.toggled()){const e=X.getUIString(this.serviceName);t.createChild("p").textContent=J(Q.recordingSActivity,{PH1:e}),t.createChild("p").textContent=J(Q.devtoolsWillRecordAllSActivity,{PH1:e})}else{const e=l.Toolbar.Toolbar.createActionButton(this.recordAction),s=document.createElement("b");s.classList.add("background-service-shortcut"),s.textContent=l.ShortcutRegistry.ShortcutRegistry.instance().shortcutsForAction("background-service.toggle-recording")[0].title();const r=l.UIUtils.createInlineButton(e);r.classList.add("background-service-record-inline-button"),t.createChild("p").appendChild(i.i18n.getFormatLocalizedString($,Q.clickTheRecordButtonSOrHitSTo,{PH1:r,PH2:s})),t.appendChild(this.createLearnMoreLink())}this.preview.show(this.previewPanel.contentElement)}async saveToFile(){const e=`${this.serviceName}-${s.DateUtilities.toISO8601Compact(new Date)}.json`,t=new p.FileUtils.FileOutputStream;if(!await t.open(e))return;const i=this.model.getEvents(this.serviceName).filter((e=>this.acceptEvent(e)));await t.write(JSON.stringify(i,void 0,2)),t.close()}wasShown(){super.wasShown(),this.registerCSSFiles([j,z])}}class Y extends m.DataGrid.DataGridNode{eventMetadata;constructor(e,t){super(e),this.eventMetadata=t.sort(((e,t)=>s.StringUtilities.compare(e.key,t.key)))}createPreview(){const e=new l.Widget.VBox;e.element.classList.add("background-service-metadata");for(const t of this.eventMetadata){const i=document.createElement("div");i.classList.add("background-service-metadata-entry"),i.createChild("div","background-service-metadata-name").textContent=t.key+": ",t.value?i.createChild("div","background-service-metadata-value source-code").textContent=t.value:i.createChild("div","background-service-metadata-value background-service-empty-value").textContent=J(Q.empty),e.element.appendChild(i)}if(!e.element.children.length){const t=document.createElement("div");t.classList.add("background-service-metadata-entry"),t.createChild("div","background-service-metadata-name background-service-empty-value").textContent=J(Q.noMetadataForThisEvent),e.element.appendChild(t)}return e}}let Z;class ee{static instance(e={forceNew:null}){const{forceNew:t}=e;return Z&&!t||(Z=new ee),Z}handleAction(e,t){const i=e.flavor(X);if("background-service.toggle-recording"===t){if(!i)throw new Error("BackgroundServiceView instance is missing");return i.toggleRecording(),!0}return!1}}var te=Object.freeze({__proto__:null,BackgroundServiceView:X,EventDataNode:Y,ActionDelegate:ee});const ie={bounceTrackingMitigations:"Bounce Tracking Mitigations"},se=i.i18n.registerUIStrings("panels/application/BounceTrackingMitigationsTreeElement.ts",ie),re=i.i18n.getLocalizedString.bind(void 0,se);class ae extends D{view;constructor(e){super(e,re(ie.bounceTrackingMitigations),!1);const t=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([t])}get itemURL(){return"bounce-tracking-mitigations://"}onselect(e){return super.onselect(e),this.view||(this.view=new oe(new u.BounceTrackingMitigationsView.BounceTrackingMitigationsView)),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.bounce_tracking_mitigations]),!1}}class oe extends l.ThrottledWidget.ThrottledWidget{bounceTrackingMitigationsView;constructor(e){super(!1),this.bounceTrackingMitigationsView=e,this.contentElement.appendChild(this.bounceTrackingMitigationsView),this.update()}async doUpdate(){this.update()}}var ne=Object.freeze({__proto__:null,i18nString:re,BounceTrackingMitigationsTreeElement:ae,BounceTrackingMitigationsViewWidgetWrapper:oe});const de=new CSSStyleSheet;de.replaceSync(".preloading-toolbar{background-color:var(--color-background-elevation-1);border-bottom:var(--legacy-divider-border)}\n/*# sourceURL=preloading/preloadingView.css */\n");const le={filterFilterByRuleSet:"Filter by rule set",filterAllRuleSets:"All rule sets",filterRuleSet:"Rule set: {PH1}",validityValid:"Valid",validityInvalid:"Invalid",validitySomeRulesInvalid:"Some rules invalid",statusNotTriggered:"Not triggered",statusPending:"Pending",statusRunning:"Running",statusReady:"Ready",statusSuccess:"Success",statusFailure:"Failure",warningTitlePreloadingDisabledByFeatureFlag:"Preloading was disabled, but is force-enabled now",warningDetailPreloadingDisabledByFeatureFlag:"Preloading is forced-enabled because DevTools is open. When DevTools is closed, prerendering will be disabled because this browser session is part of a holdback group used for performance comparisons.",warningTitlePrerenderingDisabledByFeatureFlag:"Prerendering was disabled, but is force-enabled now",warningDetailPrerenderingDisabledByFeatureFlag:"Prerendering is forced-enabled because DevTools is open. When DevTools is closed, prerendering will be disabled because this browser session is part of a holdback group used for performance comparisons.",warningTitlePreloadingStateDisabled:"Preloading is disabled",warningDetailPreloadingStateDisabled:"Preloading is disabled because of user settings or an extension. Go to {PH1} to learn more, or go to {PH2} to disable the extension.",warningDetailPreloadingDisabledByDatasaver:"Preloading is disabled because of the operating system's Data Saver mode.",warningDetailPreloadingDisabledByBatterysaver:"Preloading is disabled because of the operating system's Battery Saver mode.",preloadingPageSettings:"Preload pages settings",extensionSettings:"Extensions settings"},ce=i.i18n.registerUIStrings("panels/application/preloading/PreloadingView.ts",le),he=i.i18n.getLocalizedString.bind(void 0,ce);class ge{static action({key:e}){switch(e.action){case"Prefetch":return i.i18n.lockedString("prefetch");case"Prerender":return i.i18n.lockedString("prerender")}}static status({status:e}){switch(e){case"NotTriggered":return he(le.statusNotTriggered);case"Pending":return he(le.statusPending);case"Running":return he(le.statusRunning);case"Ready":return he(le.statusReady);case"Success":return he(le.statusSuccess);case"Failure":return he(le.statusFailure);case"NotSupported":return i.i18n.lockedString("Internal error")}}static validity({errorType:e}){switch(e){case void 0:return he(le.validityValid);case"SourceIsNotJsonObject":return he(le.validityInvalid);case"InvalidRulesSkipped":return he(le.validitySomeRulesInvalid)}}static location(e){if(void 0!==e.backendNodeId)return i.i18n.lockedString("<script>");if(void 0!==e.url)return e.url;throw Error("unreachable")}}class ue extends l.Widget.VBox{model;focusedRuleSetId=null;focusedPreloadingAttemptId=null;warningsContainer;warningsView=new we;hsplit;vsplitRuleSets;ruleSetGrid=new v.RuleSetGrid.RuleSetGrid;ruleSetDetails=new v.RuleSetDetailsReportView.RuleSetDetailsReportView;preloadingGrid=new v.PreloadingGrid.PreloadingGrid;preloadingDetails=new v.PreloadingDetailsReportView.PreloadingDetailsReportView;ruleSetSelector;constructor(e){super(!0,!1),this.model=e,o.TargetManager.TargetManager.instance().addScopeChangeListener(this.onScopeChange.bind(this)),o.TargetManager.TargetManager.instance().addModelListener(o.PreloadingModel.PreloadingModel,o.PreloadingModel.Events.ModelUpdated,this.render,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.PreloadingModel.PreloadingModel,o.PreloadingModel.Events.WarningsUpdated,this.warningsView.onWarningsUpdated,this.warningsView,{scoped:!0}),this.warningsContainer=document.createElement("div"),this.warningsContainer.classList.add("flex-none"),this.contentElement.insertBefore(this.warningsContainer,this.contentElement.firstChild),this.warningsView.show(this.warningsContainer),this.ruleSetGrid.addEventListener("cellfocused",this.onRuleSetsGridCellFocused.bind(this)),this.vsplitRuleSets=this.makeVsplit(this.ruleSetGrid,this.ruleSetDetails);const t=new l.Widget.VBox,i=new l.Toolbar.Toolbar("preloading-toolbar",t.contentElement);this.ruleSetSelector=new me((()=>this.render())),i.appendToolbarItem(this.ruleSetSelector.item()),this.preloadingGrid.addEventListener("cellfocused",this.onPreloadingGridCellFocused.bind(this));this.makeVsplit(this.preloadingGrid,this.preloadingDetails).show(t.contentElement),this.hsplit=new l.SplitWidget.SplitWidget(!1,!1,void 0,void 0,200,void 0),this.hsplit.setSidebarWidget(this.vsplitRuleSets),this.hsplit.setMainWidget(t)}makeVsplit(e,t){const i=n.LegacyWrapper.legacyWrapper(l.Widget.VBox,e);i.setMinimumSize(0,40),i.contentElement.classList.add("overflow-auto");const s=n.LegacyWrapper.legacyWrapper(l.Widget.VBox,t);s.setMinimumSize(0,80),s.contentElement.classList.add("overflow-auto");const r=new l.SplitWidget.SplitWidget(!0,!0,void 0,400,void 0,void 0);return r.setMainWidget(i),r.setSidebarWidget(s),r}wasShown(){super.wasShown(),this.registerCSSFiles([j,de]),this.hsplit.show(this.contentElement),this.render()}onScopeChange(){const e=o.TargetManager.TargetManager.instance().scopeTarget()?.model(o.PreloadingModel.PreloadingModel);r(e),this.model=e,this.render()}updateRuleSetDetails(){const e=this.focusedRuleSetId,t=null===e?null:this.model.getRuleSetById(e);this.ruleSetDetails.data=t,null===t?this.vsplitRuleSets.hideSidebar():this.vsplitRuleSets.showBoth()}updatePreloadingDetails(){const e=this.focusedPreloadingAttemptId,t=null===e?null:this.model.getPreloadingAttemptById(e);if(null===t)this.preloadingDetails.data=null;else{const e=t.ruleSetIds.map((e=>this.model.getRuleSetById(e))).filter((e=>null!==e));this.preloadingDetails.data={preloadingAttempt:t,ruleSets:e}}}render(){const t=this.model.getAllRuleSets().map((({id:e,value:t})=>({id:e,validity:ge.validity(t),location:ge.location(t)})));this.ruleSetGrid.update(t),this.updateRuleSetDetails();const i=this.ruleSetSelector.getSelected(),s=o.TargetManager.TargetManager.instance().inspectedURL(),r=s?new e.ParsedURL.ParsedURL(s).securityOrigin():null,a=this.model.getPreloadingAttempts(i).map((({id:e,value:t})=>{const i=t.key.url;return{id:e,url:r&&i.startsWith(r)?i.slice(r.length):i,action:ge.action(t),status:ge.status(t)}}));this.preloadingGrid.update(a),this.updatePreloadingDetails()}onRuleSetsGridCellFocused(e){const t=e;this.focusedRuleSetId=t.data.row.cells.find((e=>"id"===e.columnId))?.value,this.render()}onPreloadingGridCellFocused(e){const t=e;this.focusedPreloadingAttemptId=t.data.row.cells.find((e=>"id"===e.columnId))?.value,this.render()}getInfobarContainerForTest(){return this.warningsView.contentElement}getRuleSetGridForTest(){return this.ruleSetGrid}getRuleSetDetailsForTest(){return this.ruleSetDetails}getRuleSetSelectorToolbarItemForTest(){return this.ruleSetSelector.item()}getPreloadingGridForTest(){return this.preloadingGrid}getPreloadingDetailsForTest(){return this.preloadingDetails}selectRuleSetOnFilterForTest(e){this.ruleSetSelector.select(e)}}class pe extends l.Widget.VBox{model;warningsContainer;warningsView=new we;usedPreloading=new v.UsedPreloadingView.UsedPreloadingView;constructor(e){super(!0,!1),this.model=e,o.TargetManager.TargetManager.instance().addScopeChangeListener(this.onScopeChange.bind(this)),o.TargetManager.TargetManager.instance().addModelListener(o.PreloadingModel.PreloadingModel,o.PreloadingModel.Events.ModelUpdated,this.render,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.PreloadingModel.PreloadingModel,o.PreloadingModel.Events.WarningsUpdated,this.warningsView.onWarningsUpdated,this.warningsView,{scoped:!0}),this.warningsContainer=document.createElement("div"),this.warningsContainer.classList.add("flex-none"),this.contentElement.insertBefore(this.warningsContainer,this.contentElement.firstChild),this.warningsView.show(this.warningsContainer);const t=new l.Widget.VBox;t.contentElement.appendChild(this.usedPreloading),t.show(this.contentElement)}wasShown(){super.wasShown(),this.registerCSSFiles([j,de]),this.render()}onScopeChange(){const e=o.TargetManager.TargetManager.instance().scopeTarget()?.model(o.PreloadingModel.PreloadingModel);r(e),this.model=e,this.render()}render(){this.usedPreloading.data=this.model.getPreloadingAttemptsOfPreviousPage().map((({value:e})=>e))}getUsedPreloadingForTest(){return this.usedPreloading}}class me{model;onSelectionChanged=()=>{};toolbarItem;listModel;dropDown;constructor(e){const t=o.TargetManager.TargetManager.instance().scopeTarget()?.model(o.PreloadingModel.PreloadingModel);r(t),this.model=t,o.TargetManager.TargetManager.instance().addScopeChangeListener(this.onScopeChange.bind(this)),o.TargetManager.TargetManager.instance().addModelListener(o.PreloadingModel.PreloadingModel,o.PreloadingModel.Events.ModelUpdated,this.onModelUpdated,this,{scoped:!0}),this.listModel=new l.ListModel.ListModel,this.dropDown=new l.SoftDropDown.SoftDropDown(this.listModel,this),this.dropDown.setRowHeight(36),this.dropDown.setPlaceholderText(he(le.filterAllRuleSets)),this.toolbarItem=new l.Toolbar.ToolbarItem(this.dropDown.element),this.toolbarItem.setTitle(he(le.filterFilterByRuleSet)),this.toolbarItem.element.classList.add("toolbar-has-dropdown"),this.onModelUpdated(),this.onSelectionChanged=e}onScopeChange(){const e=o.TargetManager.TargetManager.instance().scopeTarget()?.model(o.PreloadingModel.PreloadingModel);r(e),this.model=e,this.onModelUpdated()}onModelUpdated(){const e=[null,...this.model.getAllRuleSets().map((({id:e})=>e))],t=this.dropDown.getSelectedItem(),i=-1===e.indexOf(t)?null:t;this.listModel.replaceAll(e),this.dropDown.selectItem(i)}getSelected(){return this.dropDown.getSelectedItem()}select(e){this.dropDown.selectItem(e)}item(){return this.toolbarItem}titleFor(e){if(null===e)return he(le.filterAllRuleSets);const t=e.indexOf("."),i=-1===t?e:e.slice(t+1);return he(le.filterRuleSet,{PH1:i})}subtitleFor(e){const t=null===e?null:this.model.getRuleSetById(e);return null===t?"":void 0!==t.url?t.url:"<script>"}createElementForItem(e){const t=document.createElement("div"),i=l.Utils.createShadowRootWithCoreStyles(t,{cssFile:void 0,delegatesFocus:void 0}),r=i.createChild("div","title");l.UIUtils.createTextChild(r,s.StringUtilities.trimEndWithMaxLength(this.titleFor(e),100));const a=i.createChild("div","subtitle");return l.UIUtils.createTextChild(a,this.subtitleFor(e)),t}isItemSelectable(e){return!0}itemSelected(e){this.onSelectionChanged()}highlightedItemChanged(e,t,i,s){}}class we extends l.Widget.VBox{constructor(){super(!1,!1)}onWarningsUpdated(e){const t=e.data,s=function(e){const t=document.createElement("div");let s=!1;if(e.disabledByPreference){const e=new w.ChromeLink.ChromeLink;e.href="chrome://settings/cookies",e.textContent=he(le.preloadingPageSettings);const r=new w.ChromeLink.ChromeLink;r.href="chrome://extensions",r.textContent=he(le.extensionSettings),t.appendChild(i.i18n.getFormatLocalizedString(ce,le.warningDetailPreloadingStateDisabled,{PH1:e,PH2:r})),s=!0}if(e.disabledByDataSaver){const e=document.createElement("div");e.append(he(le.warningDetailPreloadingDisabledByDatasaver)),t.appendChild(e),s=!0}if(e.disabledByBatterySaver){const e=document.createElement("div");e.append(he(le.warningDetailPreloadingDisabledByBatterysaver)),t.appendChild(e),s=!0}return s?t:null}(t);null!==s?this.showInfobar(he(le.warningTitlePreloadingStateDisabled),s):(t.featureFlagPreloadingHoldback&&this.showInfobar(he(le.warningTitlePreloadingDisabledByFeatureFlag),he(le.warningDetailPreloadingDisabledByFeatureFlag)),t.featureFlagPrerender2Holdback&&this.showInfobar(he(le.warningTitlePrerenderingDisabledByFeatureFlag),he(le.warningDetailPrerenderingDisabledByFeatureFlag)))}showInfobar(e,t){const i=new l.Infobar.Infobar(l.Infobar.Type.Warning,e,void 0,void 0);i.setParentView(this),i.createDetailsRowMessage(t),this.contentElement.appendChild(i.element)}}var ve=Object.freeze({__proto__:null,PreloadingView:ue,PreloadingResultView:pe,PreloadingWarningsView:we});const Se={prefetchingAndPrerendering:"Prefetching & Prerendering",thisPage:"This Page"},be=i.i18n.registerUIStrings("panels/application/PreloadingTreeElement.ts",Se),ye=i.i18n.getLocalizedString.bind(void 0,be);class ke extends D{model;ctorV;view;#e;static newForPreloadingView(e){return new ke(e,ue,ye(Se.prefetchingAndPrerendering))}static newForPreloadingResultView(e){return new ke(e,pe,ye(Se.thisPage))}constructor(e,t,i){super(e,i,!1),this.ctorV=t;const s=l.Icon.Icon.create("arrow-up-down","resource-tree-item");this.setLeadingIcons([s]),this.#e=!1}get itemURL(){return"preloading://"}initialize(e){this.model=e,this.#e&&!this.view&&this.onselect(!1)}onselect(e){return super.onselect(e),this.#e=!0,!!this.model&&(this.view||(this.view=new this.ctorV(this.model)),this.showView(this.view),!1)}}var fe=Object.freeze({__proto__:null,PreloadingTreeElement:ke});const Ce=new CSSStyleSheet;Ce.replaceSync('.tree-outline{padding-left:0;color:var(--color-text-primary)}.tree-outline > ol{padding-bottom:10px}.tree-outline li{min-height:20px}li.storage-group-list-item{padding:10px 8px 6px}li.storage-group-list-item:not(:first-child){border-top:1px solid var(--color-details-hairline)}li.storage-group-list-item::before{display:none}.icons-container [is="ui-icon"].red-icon{background-color:var(--icon-error)}[is="ui-icon"].navigator-file-tree-item{background-color:var(--icon-file-default)}[is="ui-icon"].navigator-folder-tree-item{background-color:var(--icon-folder-primary)}[is="ui-icon"].navigator-script-tree-item{background-color:var(--icon-file-script)}[is="ui-icon"].navigator-stylesheet-tree-item{background-color:var(--icon-file-styles)}[is="ui-icon"].navigator-image-tree-item,\n[is="ui-icon"].navigator-font-tree-item{background-color:var(--icon-file-image)}.window-closed .tree-element-title{text-decoration:line-through}\n/*# sourceURL=resourcesSidebar.css */\n');const Te=new CSSStyleSheet;Te.replaceSync(".service-worker-cache-data-view .data-view-toolbar{position:relative;background-color:var(--color-background-elevation-1);border-bottom:1px solid var(--color-details-hairline);padding-right:10px}.service-worker-cache-data-view .data-grid{flex:auto}.service-worker-cache-data-view .data-grid .data-container tr:nth-last-child(1) td{border:0}.service-worker-cache-data-view .data-grid .data-container tr:nth-last-child(2) td{border-bottom:1px solid var(--color-details-hairline)}.service-worker-cache-data-view .data-grid .data-container tr.selected{background-color:var(--color-background-highlight);color:inherit}.service-worker-cache-data-view .data-grid:focus .data-container tr.selected{background-color:var(--color-primary-old);color:var(--color-background)}.service-worker-cache-data-view .section,\n.service-worker-cache-data-view .section > .header,\n.service-worker-cache-data-view .section > .header .title{margin:0;min-height:inherit;line-height:inherit}.service-worker-cache-data-view .data-grid .data-container td .section .header .title{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.cache-preview-panel-resizer{background-color:var(--color-background-elevation-1);height:4px;border-bottom:1px solid var(--color-details-hairline)}.cache-storage-summary-bar{flex:0 0 27px;line-height:27px;padding-left:5px;background-color:var(--color-background-elevation-1);border-top:1px solid var(--color-details-hairline);white-space:nowrap;text-overflow:ellipsis;overflow:hidden}\n/*# sourceURL=serviceWorkerCacheViews.css */\n");const Ie={cache:"Cache",refresh:"Refresh",deleteSelected:"Delete Selected",filterByPath:"Filter by Path",selectACacheEntryAboveToPreview:"Select a cache entry above to preview",name:"Name",timeCached:"Time Cached",varyHeaderWarning:"⚠️ Set ignoreVary to true when matching this entry",serviceWorkerCache:"`Service Worker` Cache",matchingEntriesS:"Matching entries: {PH1}",totalEntriesS:"Total entries: {PH1}",headers:"Headers",preview:"Preview"},Ee=i.i18n.registerUIStrings("panels/application/ServiceWorkerCacheViews.ts",Ie),Me=i.i18n.getLocalizedString.bind(void 0,Ee);class xe extends l.View.SimpleView{model;entriesForTest;splitWidget;previewPanel;preview;cache;dataGrid;refreshThrottler;refreshButton;deleteSelectedButton;entryPathFilter;returnCount;summaryBarElement;loadingPromise;metadataView=new u.StorageMetadataView.StorageMetadataView;constructor(t,i){super(Me(Ie.cache)),this.model=t,this.entriesForTest=null,this.element.classList.add("service-worker-cache-data-view"),this.element.classList.add("storage-view");const s=new l.Toolbar.Toolbar("data-view-toolbar",this.element);this.element.appendChild(this.metadataView),this.splitWidget=new l.SplitWidget.SplitWidget(!1,!1),this.splitWidget.show(this.element),this.previewPanel=new l.Widget.VBox;const r=this.previewPanel.element.createChild("div","cache-preview-panel-resizer");this.splitWidget.setMainWidget(this.previewPanel),this.splitWidget.installResizer(r),this.preview=null,this.cache=i;const a=this.model.target().model(o.StorageBucketsModel.StorageBucketsModel)?.getBucketByName(i.storageBucket.storageKey,i.storageBucket.name);a?this.metadataView.setStorageBucket(a):i.storageKey&&this.metadataView.setStorageKey(i.storageKey),this.dataGrid=null,this.refreshThrottler=new e.Throttler.Throttler(300),this.refreshButton=new l.Toolbar.ToolbarButton(Me(Ie.refresh),"refresh"),this.refreshButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.refreshButtonClicked,this),s.appendToolbarItem(this.refreshButton),this.deleteSelectedButton=new l.Toolbar.ToolbarButton(Me(Ie.deleteSelected),"cross"),this.deleteSelectedButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,(e=>{this.deleteButtonClicked(null)})),s.appendToolbarItem(this.deleteSelectedButton);const n=new l.Toolbar.ToolbarInput(Me(Ie.filterByPath),"",1);s.appendToolbarItem(n);const d=new e.Throttler.Throttler(300);this.entryPathFilter="",n.addEventListener(l.Toolbar.ToolbarInput.Event.TextChanged,(()=>{d.schedule((()=>(this.entryPathFilter=n.value(),this.updateData(!0))))})),this.returnCount=null,this.summaryBarElement=null,this.loadingPromise=null,this.update(i)}resetDataGrid(){this.dataGrid&&this.dataGrid.asWidget().detach(),this.dataGrid=this.createDataGrid();const e=this.dataGrid.asWidget();this.splitWidget.setSidebarWidget(e),e.setMinimumSize(0,250)}wasShown(){this.model.addEventListener(o.ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,this.cacheContentUpdated,this),this.registerCSSFiles([Te]),this.updateData(!0)}willHide(){this.model.removeEventListener(o.ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,this.cacheContentUpdated,this)}showPreview(e){e&&this.preview===e||(this.preview&&this.preview.detach(),e||(e=new l.EmptyWidget.EmptyWidget(Me(Ie.selectACacheEntryAboveToPreview))),this.preview=e,this.preview.show(this.previewPanel.element))}createDataGrid(){const e=[{id:"number",title:"#",sortable:!1,width:"3px"},{id:"name",title:Me(Ie.name),weight:4,sortable:!0},{id:"responseType",title:i.i18n.lockedString("Response-Type"),weight:1,align:m.DataGrid.Align.Right,sortable:!0},{id:"contentType",title:i.i18n.lockedString("Content-Type"),weight:1,sortable:!0},{id:"contentLength",title:i.i18n.lockedString("Content-Length"),weight:1,align:m.DataGrid.Align.Right,sortable:!0},{id:"responseTime",title:Me(Ie.timeCached),width:"12em",weight:1,align:m.DataGrid.Align.Right,sortable:!0},{id:"varyHeader",title:i.i18n.lockedString("Vary Header"),weight:1,sortable:!0}],t=new m.DataGrid.DataGridImpl({displayName:Me(Ie.serviceWorkerCache),columns:e,deleteCallback:this.deleteButtonClicked.bind(this),refreshCallback:this.updateData.bind(this,!0),editCallback:void 0});return t.addEventListener(m.DataGrid.Events.SortingChanged,this.sortingChanged,this),t.addEventListener(m.DataGrid.Events.SelectedNode,(e=>{this.previewCachedResponse(e.data.data)}),this),t.setStriped(!0),t}sortingChanged(){if(!this.dataGrid)return;const e=this.dataGrid,t=e.isSortOrderAscending(),i=e.sortColumnId();let s;"name"===i?s=(e,t)=>e.name.localeCompare(t.name):"contentType"===i?s=(e,t)=>e.data.mimeType.localeCompare(t.data.mimeType):"contentLength"===i?s=(e,t)=>e.data.resourceSize-t.data.resourceSize:"responseTime"===i?s=(e,t)=>e.data.endTime-t.data.endTime:"responseType"===i?s=(e,t)=>e.responseType.localeCompare(t.responseType):"varyHeader"===i&&(s=(e,t)=>e.varyHeader.localeCompare(t.varyHeader));const r=e.rootNode().children.slice();e.rootNode().removeChildren(),r.sort(((e,i)=>{const r=s(e,i);return t?r:-r})),r.forEach((t=>e.rootNode().appendChild(t)))}async deleteButtonClicked(e){(e||(e=this.dataGrid&&this.dataGrid.selectedNode))&&(await this.model.deleteCacheEntry(this.cache,e.data.url()),e.remove())}update(e){this.cache=e,this.resetDataGrid(),this.updateData(!0)}updateSummaryBar(){this.summaryBarElement||(this.summaryBarElement=this.element.createChild("div","cache-storage-summary-bar")),this.summaryBarElement.removeChildren();const e=this.summaryBarElement.createChild("span");this.entryPathFilter?e.textContent=Me(Ie.matchingEntriesS,{PH1:String(this.returnCount)}):e.textContent=Me(Ie.totalEntriesS,{PH1:String(this.returnCount)})}updateDataCallback(e,t,i){if(!this.dataGrid)return;const s=this.dataGrid.selectedNode&&this.dataGrid.selectedNode.data.url();this.refreshButton.setEnabled(!0),this.entriesForTest=t,this.returnCount=i,this.updateSummaryBar();const r=new Map,a=this.dataGrid.rootNode();for(const e of a.children)r.set(e.data.url,e);a.removeChildren();let o=null;for(let e=0;e<t.length;++e){const i=t[e];let n=r.get(i.requestURL);n&&n.data.responseTime===i.responseTime?n.data.number=e:(n=new Le(e,this.createRequest(i),i.responseType),n.selectable=!0),a.appendChild(n),i.requestURL===s&&(o=n)}o?o.revealAndSelect():this.showPreview(null),this.updatedForTest()}async updateData(e){if(!e&&this.loadingPromise)return this.loadingPromise;if(this.refreshButton.setEnabled(!1),this.loadingPromise)return this.loadingPromise;this.loadingPromise=new Promise((e=>{this.model.loadAllCacheData(this.cache,this.entryPathFilter,((t,i)=>{e({entries:t,returnCount:i})}))}));const{entries:t,returnCount:i}=await this.loadingPromise;this.updateDataCallback(0,t,i),this.loadingPromise=null}refreshButtonClicked(){this.updateData(!0)}cacheContentUpdated(e){const{cacheName:t,storageBucket:i}=e.data;this.cache.inBucket(i)&&this.cache.cacheName===t&&this.refreshThrottler.schedule((()=>Promise.resolve(this.updateData(!0))),!0)}async previewCachedResponse(e){let t=Re.get(e);t||(t=new De(e),Re.set(e,t)),this.dataGrid&&this.dataGrid.selectedNode&&e===this.dataGrid.selectedNode.data&&this.showPreview(t)}createRequest(t){const i=o.NetworkRequest.NetworkRequest.createWithoutBackendRequest("cache-storage-"+t.requestURL,t.requestURL,s.DevToolsPath.EmptyUrlString,null);i.requestMethod=t.requestMethod,i.setRequestHeaders(t.requestHeaders),i.statusCode=t.responseStatus,i.statusText=t.responseStatusText,i.protocol=new e.ParsedURL.ParsedURL(t.requestURL).scheme,i.responseHeaders=t.responseHeaders,i.setRequestHeadersText(""),i.endTime=t.responseTime;let r=t.responseHeaders.find((e=>"content-type"===e.name.toLowerCase()));const a=r?r.value:o.NetworkRequest.MIME_TYPE.PLAIN;i.mimeType=a,r=t.responseHeaders.find((e=>"content-length"===e.name.toLowerCase())),i.resourceSize=r&&Number(r.value)||0;let n=e.ResourceType.ResourceType.fromMimeType(a);return n||(n=e.ResourceType.ResourceType.fromURL(t.requestURL)||e.ResourceType.resourceTypes.Other),i.setResourceType(n),i.setContentDataProvider(this.requestContent.bind(this,i)),i}async requestContent(e){const t=e.resourceType().isTextType(),i={error:null,content:null,encoded:!t},s=await this.cache.requestCachedResponse(e.url(),e.requestHeaders());return s&&(i.content=t?window.atob(s.body):s.body),i}updatedForTest(){}static previewSymbol=Symbol("preview")}const Re=new WeakMap;class Le extends m.DataGrid.DataGridNode{number;name;request;responseType;varyHeader;constructor(t,i,r){super(i),this.number=t;const a=new e.ParsedURL.ParsedURL(i.url());a.isValid?this.name=s.StringUtilities.trimURL(i.url(),a.domain()):this.name=i.url(),this.request=i,this.responseType=r,this.varyHeader=i.responseHeaders.find((e=>"vary"===e.name.toLowerCase()))?.value||""}createCell(e){const t=this.createTD(e);let i,s=this.request.url();"number"===e?i=String(this.number):"name"===e?i=this.name:"responseType"===e?i="opaqueResponse"===this.responseType?"opaque":"opaqueRedirect"===this.responseType?"opaqueredirect":this.responseType:"contentType"===e?i=this.request.mimeType:"contentLength"===e?i=(0|this.request.resourceSize).toLocaleString("en-US"):"responseTime"===e?i=new Date(1e3*this.request.endTime).toLocaleString():"varyHeader"===e&&(i=this.varyHeader,this.varyHeader&&(s=Me(Ie.varyHeaderWarning)));const r=t.parentElement;let a;return r&&this.dataGrid&&(a=this.dataGrid.elementToDataGridNode.get(r)),m.DataGrid.DataGridImpl.setElementText(t,i||"",!0,a),l.Tooltip.Tooltip.install(t,s),t}}class De extends l.Widget.VBox{tabbedPane;resourceViewTabSetting;constructor(t){super(),this.tabbedPane=new l.TabbedPane.TabbedPane,this.tabbedPane.addEventListener(l.TabbedPane.Events.TabSelected,this.tabSelected,this),this.resourceViewTabSetting=e.Settings.Settings.instance().createSetting("cacheStorageViewTab","preview"),this.tabbedPane.appendTab("headers",Me(Ie.headers),new S.RequestHeadersView.RequestHeadersView(t)),this.tabbedPane.appendTab("preview",Me(Ie.preview),new S.RequestPreviewView.RequestPreviewView(t)),this.tabbedPane.show(this.element)}wasShown(){super.wasShown(),this.selectTab()}selectTab(e){e||(e=this.resourceViewTabSetting.get()),e&&!this.tabbedPane.selectTab(e)&&this.tabbedPane.selectTab("headers")}tabSelected(e){e.data.isUserGesture&&this.resourceViewTabSetting.set(e.data.tabId)}}var Pe=Object.freeze({__proto__:null,ServiceWorkerCacheView:xe,DataGridNode:Le,RequestView:De});const Be={cacheStorage:"Cache Storage",refreshCaches:"Refresh Caches",delete:"Delete"},Fe=i.i18n.registerUIStrings("panels/application/ServiceWorkerCacheTreeElement.ts",Be),Ve=i.i18n.getLocalizedString.bind(void 0,Fe);class Ae extends P{swCacheModels;swCacheTreeElements;storageBucket;constructor(e,t){super(e,Ve(Be.cacheStorage),"CacheStorage");const i=l.Icon.Icon.create("database","resource-tree-item");this.setLink("https://developer.chrome.com/docs/devtools/storage/cache/?utm_source=devtools"),this.setLeadingIcons([i]),this.swCacheModels=new Set,this.swCacheTreeElements=new Set,this.storageBucket=t}initialize(){this.swCacheModels.clear(),this.swCacheTreeElements.clear(),o.TargetManager.TargetManager.instance().observeModels(o.ServiceWorkerCacheModel.ServiceWorkerCacheModel,{modelAdded:e=>this.serviceWorkerCacheModelAdded(e),modelRemoved:e=>this.serviceWorkerCacheModelRemoved(e)})}onattach(){super.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.defaultSection().appendItem(Ve(Be.refreshCaches),this.refreshCaches.bind(this)),t.show()}refreshCaches(){for(const e of this.swCacheModels)e.refreshCacheNames()}serviceWorkerCacheModelAdded(e){e.enable(),this.swCacheModels.add(e);for(const t of e.caches())this.addCache(e,t);e.addEventListener(o.ServiceWorkerCacheModel.Events.CacheAdded,this.cacheAdded,this),e.addEventListener(o.ServiceWorkerCacheModel.Events.CacheRemoved,this.cacheRemoved,this)}serviceWorkerCacheModelRemoved(e){for(const t of e.caches())this.removeCache(e,t);e.removeEventListener(o.ServiceWorkerCacheModel.Events.CacheAdded,this.cacheAdded,this),e.removeEventListener(o.ServiceWorkerCacheModel.Events.CacheRemoved,this.cacheRemoved,this),this.swCacheModels.delete(e)}cacheAdded(e){const{model:t,cache:i}=e.data;this.addCache(t,i)}addCache(e,t){const i=new Oe(this.resourcesPanel,e,t,void 0===this.storageBucket);this.swCacheTreeElements.add(i),this.appendChild(i)}cacheRemoved(e){const{model:t,cache:i}=e.data;this.removeCache(t,i)}removeCache(e,t){const i=this.cacheTreeElement(e,t);i&&(this.removeChild(i),this.swCacheTreeElements.delete(i),this.setExpandable(this.childCount()>0))}cacheTreeElement(e,t){for(const i of this.swCacheTreeElements)if(i.hasModelAndCache(e,t))return i;return null}}class Oe extends D{model;cache;view;constructor(e,t,i,s){let r;r=s?i.cacheName+" - "+i.storageKey:i.cacheName,super(e,r,!1),this.model=t,this.cache=i,this.view=null;const a=l.Icon.Icon.create("table","resource-tree-item");this.setLeadingIcons([a])}get itemURL(){return"cache://"+this.cache.cacheId}onattach(){super.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.defaultSection().appendItem(Ve(Be.delete),this.clearCache.bind(this)),t.show()}clearCache(){this.model.deleteCache(this.cache)}update(e){this.cache=e,this.view&&this.view.update(e)}onselect(e){return super.onselect(e),this.view||(this.view=new xe(this.model,this.cache)),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.service_worker_cache]),!1}hasModelAndCache(e,t){return this.cache.equals(t)&&this.model===e}}const We={databaseNoLongerHasExpected:"Database no longer has expected version.",anUnexpectedErrorSOccurred:"An unexpected error {PH1} occurred."},Ue=i.i18n.registerUIStrings("panels/application/DatabaseModel.ts",We),Ne=i.i18n.getLocalizedString.bind(void 0,Ue);class He{model;idInternal;domainInternal;nameInternal;versionInternal;constructor(e,t,i,s,r){this.model=e,this.idInternal=t,this.domainInternal=i,this.nameInternal=s,this.versionInternal=r}get id(){return this.idInternal}get name(){return this.nameInternal}set name(e){this.nameInternal=e}get version(){return this.versionInternal}set version(e){this.versionInternal=e}get domain(){return this.domainInternal}set domain(e){this.domainInternal=e}async tableNames(){const{tableNames:e}=await this.model.agent.invoke_getDatabaseTableNames({databaseId:this.idInternal})||[];return e.sort()}async executeSql(e,t,i){const s=await this.model.agent.invoke_executeSQL({databaseId:this.idInternal,query:e}),r=s.getError()||null;if(r)return void i(r);const a=s.sqlError;if(!a)return void t(s.columnNames||[],s.values||[]);let o;o=a.message?a.message:2===a.code?Ne(We.databaseNoLongerHasExpected):Ne(We.anUnexpectedErrorSOccurred,{PH1:a.code}),i(o)}}class _e extends o.SDKModel.SDKModel{databasesInternal;agent;enabled;constructor(e){super(e),this.databasesInternal=[],this.agent=e.databaseAgent(),this.target().registerDatabaseDispatcher(new qe(this))}enable(){this.enabled||(this.agent.invoke_enable(),this.enabled=!0)}disable(){this.enabled&&(this.enabled=!1,this.databasesInternal=[],this.agent.invoke_disable(),this.dispatchEventToListeners(Ge.DatabasesRemoved))}databases(){const e=[];for(const t of this.databasesInternal)e.push(t);return e}addDatabase(e){this.databasesInternal.push(e),this.dispatchEventToListeners(Ge.DatabaseAdded,e)}}var Ge;o.SDKModel.SDKModel.register(_e,{capabilities:o.Target.Capability.DOM,autostart:!1}),function(e){e.DatabaseAdded="DatabaseAdded",e.DatabasesRemoved="DatabasesRemoved"}(Ge||(Ge={}));class qe{model;constructor(e){this.model=e}addDatabase({database:e}){this.model.addDatabase(new He(this.model,e.id,e.domain,e.name,e.version))}}var Ke=Object.freeze({__proto__:null,Database:He,DatabaseModel:_e,get Events(){return Ge},DatabaseDispatcher:qe});const je={databaseQuery:"Database Query",queryS:"Query: {PH1}"},ze=i.i18n.registerUIStrings("panels/application/DatabaseQueryView.ts",je),Qe=i.i18n.getLocalizedString.bind(void 0,ze);class $e extends(e.ObjectWrapper.eventMixin(l.Widget.VBox)){database;queryWrapper;promptContainer;promptElement;prompt;proxyElement;queryResults;virtualSelectedIndex;lastSelectedElement;selectionTimeout;constructor(e){super(),this.database=e,this.element.classList.add("storage-view","query","monospace"),this.element.addEventListener("selectstart",this.selectStart.bind(this),!1),this.queryWrapper=this.element.createChild("div","database-query-group-messages"),this.queryWrapper.addEventListener("focusin",this.onFocusIn.bind(this)),this.queryWrapper.addEventListener("focusout",this.onFocusOut.bind(this)),this.queryWrapper.addEventListener("keydown",this.onKeyDown.bind(this)),this.queryWrapper.tabIndex=-1,this.promptContainer=this.element.createChild("div","database-query-prompt-container");const t=new g.Icon.Icon;t.data={iconName:"chevron-right",color:"var(--icon-action)",width:"16px",height:"16px"},t.classList.add("prompt-icon"),this.promptContainer.appendChild(t),this.promptElement=this.promptContainer.createChild("div"),this.promptElement.className="database-query-prompt",this.promptElement.addEventListener("keydown",this.promptKeyDown.bind(this)),this.prompt=new l.TextPrompt.TextPrompt,this.prompt.initialize(this.completions.bind(this)," "),this.proxyElement=this.prompt.attach(this.promptElement),this.element.addEventListener("click",this.messagesClicked.bind(this),!0),this.queryResults=[],this.virtualSelectedIndex=-1,this.selectionTimeout=0}messagesClicked(){this.prompt.focus(),this.prompt.isCaretInsidePrompt()||this.element.hasSelection()||this.prompt.moveCaretToEndOfPrompt()}onKeyDown(e){if(!l.UIUtils.isEditing()&&this.queryResults.length&&!e.shiftKey){switch(e.key){case"ArrowUp":if(!(this.virtualSelectedIndex>0))return;this.virtualSelectedIndex--;break;case"ArrowDown":if(!(this.virtualSelectedIndex<this.queryResults.length-1))return;this.virtualSelectedIndex++;break;case"Home":this.virtualSelectedIndex=0;break;case"End":this.virtualSelectedIndex=this.queryResults.length-1;break;default:return}e.consume(!0),this.updateFocusedItem()}}onFocusIn(e){-1===this.virtualSelectedIndex&&this.isOutsideViewport(e.relatedTarget)&&e.target===this.queryWrapper&&this.queryResults.length&&(this.virtualSelectedIndex=this.queryResults.length-1),this.updateFocusedItem()}onFocusOut(e){this.isOutsideViewport(e.relatedTarget)&&(this.virtualSelectedIndex=-1),this.updateFocusedItem(),this.queryWrapper.scrollTop=1e7}isOutsideViewport(e){return null!==e&&!e.isSelfOrDescendant(this.queryWrapper)}updateFocusedItem(){let e=this.virtualSelectedIndex;this.queryResults.length&&this.virtualSelectedIndex<0&&(e=this.queryResults.length-1);const t=e>=0?this.queryResults[e]:null,i=this.lastSelectedElement!==t,r=this.queryWrapper===s.DOMUtilities.deepActiveElement(this.element.ownerDocument);t&&(i||r)&&this.element.hasFocus()&&(t.hasFocus()||t.focus()),this.queryResults.length&&!this.queryWrapper.hasFocus()?this.queryWrapper.tabIndex=0:this.queryWrapper.tabIndex=-1,this.lastSelectedElement=t}async completions(e,t,i){if(!t)return[];t=t.toLowerCase();return(await this.database.tableNames()).map((e=>e+" ")).concat(Xe).filter((e=>e.toLowerCase().startsWith(t))).map((e=>({text:e})))}selectStart(e){this.selectionTimeout&&clearTimeout(this.selectionTimeout),this.prompt.clearAutocomplete(),this.selectionTimeout=window.setTimeout(function(){this.selectionTimeout=0,this.prompt.isCaretInsidePrompt()||this.element.hasSelection()||this.prompt.moveCaretToEndOfPrompt(),this.prompt.autoCompleteSoon()}.bind(this),100)}promptKeyDown(e){"Enter"!==e.key||this.enterKeyPressed(e)}async enterKeyPressed(e){e.consume(!0);const t=this.prompt.textWithCurrentSuggestion();if(this.prompt.clearAutocomplete(),t.length){this.prompt.setEnabled(!1);try{const e=await new Promise(((e,i)=>{this.database.executeSql(t,((t,i)=>e({columnNames:t,values:i})),(e=>i(e)))}));this.queryFinished(t,e.columnNames,e.values)}catch(e){this.appendErrorQueryResult(t,e)}this.prompt.setEnabled(!0),this.prompt.setText(""),this.prompt.focus()}}queryFinished(e,t,i){const s=m.SortableDataGrid.SortableDataGrid.create(t,i,Qe(je.databaseQuery)),r=e.trim();let a=null;s&&(s.setStriped(!0),s.renderInline(),s.autoSizeColumns(5),a=s.asWidget(),s.setFocusable(!1)),this.appendViewQueryResult(r,a),(r.match(/^create /i)||r.match(/^drop table /i))&&this.dispatchEventToListeners(Je.SchemaUpdated,this.database)}appendViewQueryResult(e,t){const i=this.appendQueryResult(e);t?t.show(i):i.remove(),this.scrollResultIntoView()}appendErrorQueryResult(e,t){const i=this.appendQueryResult(e);i.classList.add("error");const s=new g.Icon.Icon;s.data={iconName:"cross-circle-filled",color:"var(--icon-error)",width:"14px",height:"14px"},s.classList.add("prompt-icon"),i.appendChild(s),l.UIUtils.createTextChild(i,t),this.scrollResultIntoView()}scrollResultIntoView(){this.queryResults[this.queryResults.length-1].scrollIntoView(!1),this.promptElement.scrollIntoView(!1)}appendQueryResult(e){const t=document.createElement("div");t.className="database-user-query",t.tabIndex=-1,l.ARIAUtils.setLabel(t,Qe(je.queryS,{PH1:e})),this.queryResults.push(t),this.updateFocusedItem();const i=new g.Icon.Icon;i.data={iconName:"chevron-right",color:"var(--icon-default)",width:"16px",height:"16px"},i.classList.add("prompt-icon"),t.appendChild(i);const s=document.createElement("span");s.className="database-query-text",s.textContent=e,t.appendChild(s);const r=document.createElement("div");return r.className="database-query-result",t.appendChild(r),this.queryWrapper.appendChild(t),r}}var Je;(Je||(Je={})).SchemaUpdated="SchemaUpdated";const Xe=["SELECT ","FROM ","WHERE ","LIMIT ","DELETE FROM ","CREATE ","DROP ","TABLE ","INDEX ","UPDATE ","INSERT INTO ","VALUES ("];var Ye=Object.freeze({__proto__:null,DatabaseQueryView:$e,get Events(){return Je},SQL_BUILT_INS:Xe});const Ze={database:"Database",refresh:"Refresh",visibleColumns:"Visible columns",theStableIsEmpty:'The "{PH1}" table is empty.',anErrorOccurredTryingToreadTheS:'An error occurred trying to read the "{PH1}" table.'},et=i.i18n.registerUIStrings("panels/application/DatabaseTableView.ts",Ze),tt=i.i18n.getLocalizedString.bind(void 0,et);class it extends l.View.SimpleView{database;tableName;lastVisibleColumns;columnsMap;visibleColumnsSetting;refreshButton;visibleColumnsInput;dataGrid;emptyWidget;constructor(t,i){super(tt(Ze.database)),this.database=t,this.tableName=i,this.lastVisibleColumns="",this.columnsMap=new Map,this.element.classList.add("storage-view","table"),this.visibleColumnsSetting=e.Settings.Settings.instance().createSetting("databaseTableViewVisibleColumns",{}),this.refreshButton=new l.Toolbar.ToolbarButton(tt(Ze.refresh),"refresh"),this.refreshButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.refreshButtonClicked,this),this.visibleColumnsInput=new l.Toolbar.ToolbarInput(tt(Ze.visibleColumns),"",1),this.visibleColumnsInput.addEventListener(l.Toolbar.ToolbarInput.Event.TextChanged,this.onVisibleColumnsChanged,this),this.dataGrid=null}wasShown(){this.update()}async toolbarItems(){return[this.refreshButton,this.visibleColumnsInput]}escapeTableName(e){return e.replace(/\"/g,'""')}update(){this.database.executeSql('SELECT rowid, * FROM "'+this.escapeTableName(this.tableName)+'"',this.queryFinished.bind(this),this.queryError.bind(this))}queryFinished(e,t){if(this.detachChildWidgets(),this.element.removeChildren(),this.dataGrid=m.SortableDataGrid.SortableDataGrid.create(e,t,tt(Ze.database)),this.visibleColumnsInput.setVisible(Boolean(this.dataGrid)),!this.dataGrid)return this.emptyWidget=new l.EmptyWidget.EmptyWidget(tt(Ze.theStableIsEmpty,{PH1:this.tableName})),void this.emptyWidget.show(this.element);this.dataGrid.setStriped(!0),this.dataGrid.asWidget().show(this.element),this.dataGrid.autoSizeColumns(5),this.columnsMap.clear();for(let t=1;t<e.length;++t)this.columnsMap.set(e[t],String(t));this.lastVisibleColumns="";const i=this.visibleColumnsSetting.get()[this.tableName]||"";this.visibleColumnsInput.setValue(i),this.onVisibleColumnsChanged()}onVisibleColumnsChanged(){if(!this.dataGrid)return;const e=this.visibleColumnsInput.value(),t=e.split(/[\s,]+/),i=new Set,s=new Set;s.add("0");for(const e of t){const t=this.columnsMap.get(e);void 0!==t&&(i.add(e),s.add(t))}const r=[...i].sort().join(", ");if(0===r.length)for(const e of this.columnsMap.values())s.add(e);if(r===this.lastVisibleColumns)return;const a=this.visibleColumnsSetting.get();a[this.tableName]=e,this.visibleColumnsSetting.set(a),this.dataGrid.setColumnsVisiblity(s),this.lastVisibleColumns=r}queryError(){this.detachChildWidgets(),this.element.removeChildren();const e=document.createElement("div");e.className="storage-table-error",e.textContent=tt(Ze.anErrorOccurredTryingToreadTheS,{PH1:this.tableName}),this.element.appendChild(e)}refreshButtonClicked(){this.update()}}var st,rt=Object.freeze({__proto__:null,DatabaseTableView:it});class at extends e.ObjectWrapper.ObjectWrapper{model;storageKeyInternal;isLocalStorageInternal;constructor(e,t,i){super(),this.model=e,this.storageKeyInternal=t,this.isLocalStorageInternal=i}static storageId(e,t){return{storageKey:e,isLocalStorage:t}}get id(){return at.storageId(this.storageKeyInternal,this.isLocalStorageInternal)}get storageKey(){return this.storageKeyInternal}get isLocalStorage(){return this.isLocalStorageInternal}getItems(){return this.model.agent.invoke_getDOMStorageItems({storageId:this.id}).then((({entries:e})=>e))}setItem(e,t){this.model.agent.invoke_setDOMStorageItem({storageId:this.id,key:e,value:t})}removeItem(e){this.model.agent.invoke_removeDOMStorageItem({storageId:this.id,key:e})}clear(){this.model.agent.invoke_clear({storageId:this.id})}}!function(e){let t;!function(e){e.DOMStorageItemsCleared="DOMStorageItemsCleared",e.DOMStorageItemRemoved="DOMStorageItemRemoved",e.DOMStorageItemAdded="DOMStorageItemAdded",e.DOMStorageItemUpdated="DOMStorageItemUpdated"}(t=e.Events||(e.Events={}))}(at||(at={}));class ot extends o.SDKModel.SDKModel{storageKeyManagerInternal;storagesInternal;agent;enabled;constructor(e){super(e),this.storageKeyManagerInternal=e.model(o.StorageKeyManager.StorageKeyManager),this.storagesInternal={},this.agent=e.domstorageAgent()}get storageKeyManagerForTest(){return this.storageKeyManagerInternal}enable(){if(!this.enabled){if(this.target().registerDOMStorageDispatcher(new nt(this)),this.storageKeyManagerInternal){this.storageKeyManagerInternal.addEventListener(o.StorageKeyManager.Events.StorageKeyAdded,this.storageKeyAdded,this),this.storageKeyManagerInternal.addEventListener(o.StorageKeyManager.Events.StorageKeyRemoved,this.storageKeyRemoved,this);for(const e of this.storageKeyManagerInternal.storageKeys())this.addStorageKey(e)}this.agent.invoke_enable(),this.enabled=!0}}clearForStorageKey(e){if(this.enabled){for(const t of[!0,!1]){const i=this.storageKey(e,t),s=this.storagesInternal[i];if(!s)return;s.clear()}this.removeStorageKey(e),this.addStorageKey(e)}}storageKeyAdded(e){this.addStorageKey(e.data)}addStorageKey(e){for(const t of[!0,!1]){const i=this.storageKey(e,t);console.assert(!this.storagesInternal[i]);const s=new at(this,e,t);this.storagesInternal[i]=s,this.dispatchEventToListeners(st.DOMStorageAdded,s)}}storageKeyRemoved(e){this.removeStorageKey(e.data)}removeStorageKey(e){for(const t of[!0,!1]){const i=this.storageKey(e,t),s=this.storagesInternal[i];s&&(delete this.storagesInternal[i],this.dispatchEventToListeners(st.DOMStorageRemoved,s))}}storageKey(e,t){return JSON.stringify(at.storageId(e,t))}domStorageItemsCleared(e){const t=this.storageForId(e);t&&t.dispatchEventToListeners(at.Events.DOMStorageItemsCleared)}domStorageItemRemoved(e,t){const i=this.storageForId(e);if(!i)return;const s={key:t};i.dispatchEventToListeners(at.Events.DOMStorageItemRemoved,s)}domStorageItemAdded(e,t,i){const s=this.storageForId(e);if(!s)return;const r={key:t,value:i};s.dispatchEventToListeners(at.Events.DOMStorageItemAdded,r)}domStorageItemUpdated(e,t,i,s){const r=this.storageForId(e);if(!r)return;const a={key:t,oldValue:i,value:s};r.dispatchEventToListeners(at.Events.DOMStorageItemUpdated,a)}storageForId(e){return console.assert(Boolean(e.storageKey)),this.storagesInternal[this.storageKey(e.storageKey||"",e.isLocalStorage)]}storages(){const e=[];for(const t in this.storagesInternal)e.push(this.storagesInternal[t]);return e}}o.SDKModel.SDKModel.register(ot,{capabilities:o.Target.Capability.DOM,autostart:!1}),function(e){e.DOMStorageAdded="DOMStorageAdded",e.DOMStorageRemoved="DOMStorageRemoved"}(st||(st={}));class nt{model;constructor(e){this.model=e}domStorageItemsCleared({storageId:e}){this.model.domStorageItemsCleared(e)}domStorageItemRemoved({storageId:e,key:t}){this.model.domStorageItemRemoved(e,t)}domStorageItemAdded({storageId:e,key:t,newValue:i}){this.model.domStorageItemAdded(e,t,i)}domStorageItemUpdated({storageId:e,key:t,oldValue:i,newValue:s}){this.model.domStorageItemUpdated(e,t,i,s)}}var dt=Object.freeze({__proto__:null,get DOMStorage(){return at},DOMStorageModel:ot,get Events(){return st},DOMStorageDispatcher:nt});class lt extends o.SDKModel.SDKModel{storageBucketModel;indexedDBAgent;storageAgent;databasesInternal;databaseNamesByStorageKeyAndBucket;updatedStorageBuckets;throttler;enabled;constructor(t){super(t),t.registerStorageDispatcher(this),this.storageBucketModel=t.model(o.StorageBucketsModel.StorageBucketsModel),this.indexedDBAgent=t.indexedDBAgent(),this.storageAgent=t.storageAgent(),this.databasesInternal=new Map,this.databaseNamesByStorageKeyAndBucket=new Map,this.updatedStorageBuckets=new Set,this.throttler=new e.Throttler.Throttler(1e3)}static keyFromIDBKey(e){if(null==e)return;let t;switch(typeof e){case"number":t={type:"number",number:e};break;case"string":t={type:"string",string:e};break;case"object":if(e instanceof Date)t={type:"date",date:e.getTime()};else{if(!Array.isArray(e))return;{const i=[];for(let t=0;t<e.length;++t){const s=lt.keyFromIDBKey(e[t]);s&&i.push(s)}t={type:"array",array:i}}}break;default:return}return t}static keyRangeFromIDBKeyRange(e){return{lower:lt.keyFromIDBKey(e.lower),upper:lt.keyFromIDBKey(e.upper),lowerOpen:Boolean(e.lowerOpen),upperOpen:Boolean(e.upperOpen)}}static idbKeyPathFromKeyPath(e){let t;switch(e.type){case"null":t=null;break;case"string":t=e.string;break;case"array":t=e.array}return t}static keyPathStringFromIDBKeyPath(e){return"string"==typeof e?'"'+e+'"':e instanceof Array?'["'+e.join('", "')+'"]':null}enable(){if(!this.enabled){if(this.indexedDBAgent.invoke_enable(),this.storageBucketModel){this.storageBucketModel.addEventListener("BucketAdded",this.storageBucketAdded,this),this.storageBucketModel.addEventListener("BucketRemoved",this.storageBucketRemoved,this);for(const{bucket:e}of this.storageBucketModel.getBuckets())this.addStorageBucket(e)}this.enabled=!0}}clearForStorageKey(e){if(!this.enabled||!this.databaseNamesByStorageKeyAndBucket.has(e))return;for(const[t]of this.databaseNamesByStorageKeyAndBucket.get(e)||[]){const i=this.storageBucketModel?.getBucketByName(e,t??void 0)?.bucket;i&&this.removeStorageBucket(i)}this.databaseNamesByStorageKeyAndBucket.delete(e);const t=this.storageBucketModel?.getBucketsForStorageKey(e)||[];for(const{bucket:e}of t)this.addStorageBucket(e)}async deleteDatabase(e){this.enabled&&(await this.indexedDBAgent.invoke_deleteDatabase({storageBucket:e.storageBucket,databaseName:e.name}),this.loadDatabaseNamesByStorageBucket(e.storageBucket))}async refreshDatabaseNames(){for(const[e]of this.databaseNamesByStorageKeyAndBucket){const t=this.databaseNamesByStorageKeyAndBucket.get(e)?.keys()||[];for(const i of t){const t=this.storageBucketModel?.getBucketByName(e,i??void 0)?.bucket;t&&await this.loadDatabaseNamesByStorageBucket(t)}}this.dispatchEventToListeners(ct.DatabaseNamesRefreshed)}refreshDatabase(e){this.loadDatabase(e,!0)}async clearObjectStore(e,t){await this.indexedDBAgent.invoke_clearObjectStore({storageBucket:e.storageBucket,databaseName:e.name,objectStoreName:t})}async deleteEntries(e,t,i){const s=lt.keyRangeFromIDBKeyRange(i);await this.indexedDBAgent.invoke_deleteObjectStoreEntries({storageBucket:e.storageBucket,databaseName:e.name,objectStoreName:t,keyRange:s})}storageBucketAdded({data:{bucketInfo:{bucket:e}}}){this.addStorageBucket(e)}storageBucketRemoved({data:{bucketInfo:{bucket:e}}}){this.removeStorageBucket(e)}addStorageBucket(e){const{storageKey:t}=e;this.databaseNamesByStorageKeyAndBucket.has(t)||(this.databaseNamesByStorageKeyAndBucket.set(t,new Map),this.storageAgent.invoke_trackIndexedDBForStorageKey({storageKey:t}));const i=this.databaseNamesByStorageKeyAndBucket.get(t)||new Map;console.assert(!i.has(e.name??"")),i.set(e.name??"",new Set),this.loadDatabaseNamesByStorageBucket(e)}removeStorageBucket(e){const{storageKey:t}=e;console.assert(this.databaseNamesByStorageKeyAndBucket.has(t));const i=this.databaseNamesByStorageKeyAndBucket.get(t)||new Map;console.assert(i.has(e.name??""));const s=i.get(e.name??"")||new Map;for(const e of s)this.databaseRemovedForStorageBucket(e);i.delete(e.name??""),0===i.size&&(this.databaseNamesByStorageKeyAndBucket.delete(t),this.storageAgent.invoke_untrackIndexedDBForStorageKey({storageKey:t}))}updateStorageKeyDatabaseNames(e,t){const i=this.databaseNamesByStorageKeyAndBucket.get(e.storageKey);if(void 0===i)return;const s=new Set(t.map((t=>new gt(e,t)))),r=new Set(i.get(e.name??""));i.set(e.name??"",s);for(const e of r)e.inSet(s)||this.databaseRemovedForStorageBucket(e);for(const e of s)e.inSet(r)||this.databaseAddedForStorageBucket(e)}databases(){const e=[];for(const[,t]of this.databaseNamesByStorageKeyAndBucket)for(const[,i]of t)for(const t of i)e.push(t);return e}databaseAddedForStorageBucket(e){this.dispatchEventToListeners(ct.DatabaseAdded,{model:this,databaseId:e})}databaseRemovedForStorageBucket(e){this.dispatchEventToListeners(ct.DatabaseRemoved,{model:this,databaseId:e})}async loadDatabaseNamesByStorageBucket(e){const{storageKey:t}=e,{databaseNames:i}=await this.indexedDBAgent.invoke_requestDatabaseNames({storageBucket:e});if(!i)return[];if(!this.databaseNamesByStorageKeyAndBucket.has(t))return[];return(this.databaseNamesByStorageKeyAndBucket.get(t)||new Map).has(e.name??"")?(this.updateStorageKeyDatabaseNames(e,i),i):[]}async loadDatabase(e,t){const i=(await this.indexedDBAgent.invoke_requestDatabase({storageBucket:e.storageBucket,databaseName:e.name})).databaseWithObjectStores;if(!this.databaseNamesByStorageKeyAndBucket.get(e.storageBucket.storageKey)?.has(e.storageBucket.name??""))return;if(!i)return;const s=new ut(e,i.version);this.databasesInternal.set(e,s);for(const e of i.objectStores){const t=lt.idbKeyPathFromKeyPath(e.keyPath),i=new pt(e.name,t,e.autoIncrement);for(let t=0;t<e.indexes.length;++t){const s=e.indexes[t],r=lt.idbKeyPathFromKeyPath(s.keyPath),a=new mt(s.name,r,s.unique,s.multiEntry);i.indexes.set(a.name,a)}s.objectStores.set(i.name,i)}this.dispatchEventToListeners(ct.DatabaseLoaded,{model:this,database:s,entriesUpdated:t})}loadObjectStoreData(e,t,i,s,r,a){this.requestData(e,e.name,t,"",i,s,r,a)}loadIndexData(e,t,i,s,r,a,o){this.requestData(e,e.name,t,i,s,r,a,o)}async requestData(e,t,i,s,r,a,n,d){const l=r?lt.keyRangeFromIDBKeyRange(r):void 0,c=this.target().model(o.RuntimeModel.RuntimeModel),h=await this.indexedDBAgent.invoke_requestData({storageBucket:e.storageBucket,databaseName:t,objectStoreName:i,indexName:s,skipCount:a,pageSize:n,keyRange:l});if(!c||!this.databaseNamesByStorageKeyAndBucket.get(e.storageBucket.storageKey)?.has(e.storageBucket.name??""))return;if(h.getError())return void console.error("IndexedDBAgent error: "+h.getError());const g=h.objectStoreDataEntries,u=[];for(const e of g){const t=c?.createRemoteObject(e.key),i=c?.createRemoteObject(e.primaryKey),s=c?.createRemoteObject(e.value);if(!t||!i||!s)return;u.push(new ht(t,i,s))}d(u,h.hasMore)}async getMetadata(e,t){const i=e.name,s=t.name,r=await this.indexedDBAgent.invoke_getMetadata({storageBucket:e.storageBucket,databaseName:i,objectStoreName:s});return r.getError()?(console.error("IndexedDBAgent error: "+r.getError()),null):{entriesCount:r.entriesCount,keyGeneratorValue:r.keyGeneratorValue}}async refreshDatabaseListForStorageBucket(e){const t=await this.loadDatabaseNamesByStorageBucket(e);for(const i of t)this.loadDatabase(new gt(e,i),!1)}indexedDBListUpdated({storageKey:e,bucketId:t}){const i=this.storageBucketModel?.getBucketById(t)?.bucket;e&&i&&(this.updatedStorageBuckets.add(i),this.throttler.schedule((()=>{const e=Array.from(this.updatedStorageBuckets,(e=>{this.refreshDatabaseListForStorageBucket(e)}));return this.updatedStorageBuckets.clear(),Promise.all(e)})))}indexedDBContentUpdated({bucketId:e,databaseName:t,objectStoreName:i}){const s=this.storageBucketModel?.getBucketById(e)?.bucket;if(s){const e=new gt(s,t);this.dispatchEventToListeners(ct.IndexedDBContentUpdated,{databaseId:e,objectStoreName:i,model:this})}}cacheStorageListUpdated(e){}cacheStorageContentUpdated(e){}interestGroupAccessed(e){}sharedStorageAccessed(e){}storageBucketCreatedOrUpdated(e){}storageBucketDeleted(e){}}var ct;o.SDKModel.SDKModel.register(lt,{capabilities:o.Target.Capability.Storage,autostart:!1}),function(e){e.DatabaseAdded="DatabaseAdded",e.DatabaseRemoved="DatabaseRemoved",e.DatabaseLoaded="DatabaseLoaded",e.DatabaseNamesRefreshed="DatabaseNamesRefreshed",e.IndexedDBContentUpdated="IndexedDBContentUpdated"}(ct||(ct={}));class ht{key;primaryKey;value;constructor(e,t,i){this.key=e,this.primaryKey=t,this.value=i}}class gt{storageBucket;name;constructor(e,t){this.storageBucket=e,this.name=t}equals(e){return this.name===e.name&&this.storageBucket.name===e.storageBucket.name&&this.storageBucket.storageKey===e.storageBucket.storageKey}inSet(e){for(const t of e)if(this.equals(t))return!0;return!1}}class ut{databaseId;version;objectStores;constructor(e,t){this.databaseId=e,this.version=t,this.objectStores=new Map}}class pt{name;keyPath;autoIncrement;indexes;constructor(e,t,i){this.name=e,this.keyPath=t,this.autoIncrement=i,this.indexes=new Map}get keyPathString(){return lt.keyPathStringFromIDBKeyPath(this.keyPath)}}class mt{name;keyPath;unique;multiEntry;constructor(e,t,i,s){this.name=e,this.keyPath=t,this.unique=i,this.multiEntry=s}get keyPathString(){return lt.keyPathStringFromIDBKeyPath(this.keyPath)}}var wt=Object.freeze({__proto__:null,IndexedDBModel:lt,get Events(){return ct},Entry:ht,DatabaseId:gt,Database:ut,ObjectStore:pt,Index:mt});const vt=new CSSStyleSheet;vt.replaceSync('.indexed-db-data-view .data-view-toolbar{position:relative;background-color:var(--color-background-elevation-1);border-bottom:1px solid var(--color-details-hairline)}.indexed-db-data-view .data-grid{flex:auto}.indexed-db-data-view .data-grid .data-container tr:nth-last-child(1){background-color:var(--color-background)}.indexed-db-data-view .data-grid .data-container tr:nth-last-child(1) td{border:0}.indexed-db-data-view .data-grid .data-container tr:nth-last-child(2) td{border-bottom:1px solid var(--color-details-hairline)}.indexed-db-data-view .data-grid:focus .data-container tr.selected{background-color:var(--color-background-highlight);color:inherit}.indexed-db-data-view .section,\n.indexed-db-data-view .section > .header,\n.indexed-db-data-view .section > .header .title{margin:0;min-height:inherit;line-height:inherit}.indexed-db-data-view .data-grid .data-container td .section .header .title{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.indexed-db-key-path{color:var(--color-accent-red);white-space:pre-wrap;unicode-bidi:-webkit-isolate}.indexed-db-container{overflow:auto}.indexed-db-header{min-width:400px;flex-shrink:0;flex-grow:0}[is="ui-icon"].warning.icon-mask{background-color:var(--icon-warning)}.source-code.indexed-db-key-path{font-size:unset!important}.resources-toolbar{padding-right:10px}.object-store-summary-bar{flex:0 0 27px;line-height:27px;padding-left:5px;background-color:var(--color-background-elevation-1);border-top:1px solid var(--color-details-hairline);white-space:nowrap;text-overflow:ellipsis;overflow:hidden}\n/*# sourceURL=indexedDBViews.css */\n');const St={version:"Version",objectStores:"Object stores",deleteDatabase:"Delete database",refreshDatabase:"Refresh database",pleaseConfirmDeleteOfSDatabase:'Please confirm delete of "{PH1}" database.',idb:"IDB",refresh:"Refresh",deleteSelected:"Delete selected",clearObjectStore:"Clear object store",dataMayBeStale:"Data may be stale",someEntriesMayHaveBeenModified:"Some entries may have been modified",keyString:"Key",primaryKey:"Primary key",valueString:"Value",indexedDb:"Indexed DB",keyPath:"Key path: ",showPreviousPage:"Show previous page",showNextPage:"Show next page",startFromKey:"Start from key",expandRecursively:"Expand Recursively",collapse:"Collapse",totalEntriesS:"Total entries: {PH1}",keyGeneratorValueS:"Key generator value: {PH1}"},bt=i.i18n.registerUIStrings("panels/application/IndexedDBViews.ts",St),yt=i.i18n.getLocalizedString.bind(void 0,bt);class kt extends u.StorageMetadataView.StorageMetadataView{model;database;constructor(e,t){super(),this.model=e,t&&this.update(t)}getTitle(){return this.database?.databaseId.name}async renderReportContent(){return this.database?C.html` ${await super.renderReportContent()} ${this.key(yt(St.version))} ${this.value(this.database.version.toString())} ${this.key(yt(St.objectStores))} ${this.value(this.database.objectStores.size.toString())} <${k.ReportView.ReportSectionDivider.litTagName}></${k.ReportView.ReportSectionDivider.litTagName}> <${k.ReportView.ReportSection.litTagName}> <${b.Button.Button.litTagName} aria-label="${yt(St.deleteDatabase)}" .variant="${"secondary"}" @click="${this.deleteDatabase}"> ${yt(St.deleteDatabase)} </${b.Button.Button.litTagName}> <${b.Button.Button.litTagName} aria-label="${yt(St.refreshDatabase)}" .variant="${"secondary"}" @click="${this.refreshDatabaseButtonClicked}"> ${yt(St.refreshDatabase)} </${b.Button.Button.litTagName}> </${k.ReportView.ReportSection.litTagName}> `:C.nothing}refreshDatabaseButtonClicked(){this.model.refreshDatabase(this.database.databaseId)}update(e){this.database=e;const t=this.model.target().model(o.StorageBucketsModel.StorageBucketsModel)?.getBucketByName(e.databaseId.storageBucket.storageKey,e.databaseId.storageBucket.name);t?this.setStorageBucket(t):this.setStorageKey(e.databaseId.storageBucket.storageKey),this.render().then((()=>this.updatedForTests()))}updatedForTests(){}async deleteDatabase(){await l.UIUtils.ConfirmDialog.show(yt(St.pleaseConfirmDeleteOfSDatabase,{PH1:this.database.databaseId.name}),this)&&this.model.deleteDatabase(this.database.databaseId)}wasShown(){super.wasShown()}}y.CustomElements.defineComponent("devtools-idb-database-view",kt);class ft extends l.View.SimpleView{model;databaseId;isIndex;refreshObjectStoreCallback;refreshButton;deleteSelectedButton;clearButton;needsRefresh;clearingObjectStore;pageSize;skipCount;entries;objectStore;index;keyInput;dataGrid;lastPageSize;lastSkipCount;pageBackButton;pageForwardButton;lastKey;summaryBarElement;constructor(e,t,i,s,r){super(yt(St.idb)),this.model=e,this.databaseId=t,this.isIndex=Boolean(s),this.refreshObjectStoreCallback=r,this.element.classList.add("indexed-db-data-view","storage-view"),this.refreshButton=new l.Toolbar.ToolbarButton(yt(St.refresh),"refresh"),this.refreshButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.refreshButtonClicked,this),this.deleteSelectedButton=new l.Toolbar.ToolbarButton(yt(St.deleteSelected),"cross"),this.deleteSelectedButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,(e=>{this.deleteButtonClicked(null)})),this.clearButton=new l.Toolbar.ToolbarButton(yt(St.clearObjectStore),"clear"),this.clearButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,(()=>{this.clearButtonClicked()}),this);const a=l.UIUtils.createIconLabel({title:yt(St.dataMayBeStale),iconName:"warning",color:"var(--icon-warning)",width:"20px",height:"20px"});this.needsRefresh=new l.Toolbar.ToolbarItem(a),this.needsRefresh.setVisible(!1),this.needsRefresh.setTitle(yt(St.someEntriesMayHaveBeenModified)),this.clearingObjectStore=!1,this.createEditorToolbar(),this.pageSize=50,this.skipCount=0,this.update(i,s),this.entries=[]}createDataGrid(){const e=this.isIndex&&this.index?this.index.keyPath:this.objectStore.keyPath,t=[],i={title:void 0,titleDOMFragment:void 0,sortable:!1,sort:void 0,align:void 0,width:void 0,fixedWidth:void 0,editable:void 0,nonSelectable:void 0,longText:void 0,disclosure:void 0,weight:void 0,allowInSortByEvenWhenHidden:void 0,dataType:void 0,defaultWeight:void 0};t.push({...i,id:"number",title:"#",sortable:!1,width:"50px"}),t.push({...i,id:"key",titleDOMFragment:this.keyColumnHeaderFragment(yt(St.keyString),e),sortable:!1}),this.isIndex&&t.push({...i,id:"primaryKey",titleDOMFragment:this.keyColumnHeaderFragment(yt(St.primaryKey),this.objectStore.keyPath),sortable:!1});const s=yt(St.valueString);t.push({...i,id:"value",title:s,sortable:!1});const r=new m.DataGrid.DataGridImpl({displayName:yt(St.indexedDb),columns:t,deleteCallback:this.deleteButtonClicked.bind(this),refreshCallback:this.updateData.bind(this,!0),editCallback:void 0});return r.setStriped(!0),r.addEventListener(m.DataGrid.Events.SelectedNode,(()=>this.updateToolbarEnablement()),this),r}keyColumnHeaderFragment(e,t){const i=document.createDocumentFragment();if(l.UIUtils.createTextChild(i,e),null===t)return i;if(l.UIUtils.createTextChild(i," ("+yt(St.keyPath)),Array.isArray(t)){l.UIUtils.createTextChild(i,"[");for(let e=0;e<t.length;++e)0!==e&&l.UIUtils.createTextChild(i,", "),i.appendChild(this.keyPathStringFragment(t[e]));l.UIUtils.createTextChild(i,"]")}else{const e=t;i.appendChild(this.keyPathStringFragment(e))}return l.UIUtils.createTextChild(i,")"),i}keyPathStringFragment(e){const t=document.createDocumentFragment();l.UIUtils.createTextChild(t,'"');return t.createChild("span","source-code indexed-db-key-path").textContent=e,l.UIUtils.createTextChild(t,'"'),t}createEditorToolbar(){const e=new l.Toolbar.Toolbar("data-view-toolbar",this.element);e.appendToolbarItem(this.refreshButton),e.appendToolbarItem(new l.Toolbar.ToolbarSeparator);const t=new g.Icon.Icon;t.data={iconName:"triangle-left",color:"var(--icon-default)",width:"20px",height:"20px"},this.pageBackButton=new l.Toolbar.ToolbarButton(yt(St.showPreviousPage),t),this.pageBackButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.pageBackButtonClicked,this),e.appendToolbarItem(this.pageBackButton);const i=new g.Icon.Icon;i.data={iconName:"triangle-right",color:"var(--icon-default)",width:"20px",height:"20px"},this.pageForwardButton=new l.Toolbar.ToolbarButton(yt(St.showNextPage),i),this.pageForwardButton.setEnabled(!1),this.pageForwardButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.pageForwardButtonClicked,this),e.appendToolbarItem(this.pageForwardButton),this.keyInput=new l.Toolbar.ToolbarInput(yt(St.startFromKey),"",.5),this.keyInput.addEventListener(l.Toolbar.ToolbarInput.Event.TextChanged,this.updateData.bind(this,!1)),e.appendToolbarItem(this.keyInput),e.appendToolbarItem(new l.Toolbar.ToolbarSeparator),e.appendToolbarItem(this.clearButton),e.appendToolbarItem(this.deleteSelectedButton),e.appendToolbarItem(this.needsRefresh)}pageBackButtonClicked(){this.skipCount=Math.max(0,this.skipCount-this.pageSize),this.updateData(!1)}pageForwardButtonClicked(){this.skipCount=this.skipCount+this.pageSize,this.updateData(!1)}populateContextMenu(e,t){const i=t;i.valueObjectPresentation&&(e.revealSection().appendItem(yt(St.expandRecursively),(()=>{i.valueObjectPresentation&&i.valueObjectPresentation.objectTreeElement().expandRecursively()})),e.revealSection().appendItem(yt(St.collapse),(()=>{i.valueObjectPresentation&&i.valueObjectPresentation.objectTreeElement().collapse()})))}refreshData(){this.updateData(!0)}update(e,t){this.objectStore=e,this.index=t,this.dataGrid&&this.dataGrid.asWidget().detach(),this.dataGrid=this.createDataGrid(),this.dataGrid.setRowContextMenuCallback(this.populateContextMenu.bind(this)),this.dataGrid.asWidget().show(this.element),this.skipCount=0,this.updateData(!0)}parseKey(e){let t;try{t=JSON.parse(e)}catch(i){t=e}return t}updateData(e){const t=this.parseKey(this.keyInput.value()),i=this.pageSize;let s=this.skipCount,r=this.dataGrid.selectedNode?this.dataGrid.selectedNode.data.number:0;if(r=Math.max(r,this.skipCount),this.clearButton.setEnabled(!this.isIndex),!e&&this.lastKey===t&&this.lastPageSize===i&&this.lastSkipCount===s)return;function a(e,t){this.clear(),this.entries=e;let i=null;for(let t=0;t<e.length;++t){const a={};a.number=t+s,a.key=e[t].key,a.primaryKey=e[t].primaryKey,a.value=e[t].value;const o=new Ct(a);this.dataGrid.rootNode().appendChild(o),a.number<=r&&(i=o)}i&&i.select(),this.pageBackButton.setEnabled(Boolean(s)),this.pageForwardButton.setEnabled(t),this.needsRefresh.setVisible(!1),this.updateToolbarEnablement(),this.updatedDataForTests()}this.lastKey===t&&this.lastPageSize===i||(s=0,this.skipCount=0),this.lastKey=t,this.lastPageSize=i,this.lastSkipCount=s;const o=t?window.IDBKeyRange.lowerBound(t):null;this.isIndex&&this.index?this.model.loadIndexData(this.databaseId,this.objectStore.name,this.index.name,o,s,i,a.bind(this)):this.model.loadObjectStoreData(this.databaseId,this.objectStore.name,o,s,i,a.bind(this)),this.model.getMetadata(this.databaseId,this.objectStore).then(this.updateSummaryBar.bind(this))}updateSummaryBar(e){if(this.summaryBarElement||(this.summaryBarElement=this.element.createChild("div","object-store-summary-bar")),this.summaryBarElement.removeChildren(),!e)return;const t=this.summaryBarElement.createChild("span");t.textContent=yt(St.totalEntriesS,{PH1:String(e.entriesCount)}),this.objectStore.autoIncrement&&(t.textContent+=" ❘ ",t.textContent+=yt(St.keyGeneratorValueS,{PH1:String(e.keyGeneratorValue)}))}updatedDataForTests(){}refreshButtonClicked(){this.updateData(!0)}async clearButtonClicked(){this.clearButton.setEnabled(!1),this.clearingObjectStore=!0,await this.model.clearObjectStore(this.databaseId,this.objectStore.name),this.clearingObjectStore=!1,this.clearButton.setEnabled(!0),this.updateData(!0)}markNeedsRefresh(){this.clearingObjectStore||this.needsRefresh.setVisible(!0)}async deleteButtonClicked(e){if(!e&&!(e=this.dataGrid.selectedNode))return;const t=(this.isIndex?e.data.primaryKey:e.data.key).value;await this.model.deleteEntries(this.databaseId,this.objectStore.name,window.IDBKeyRange.only(t)),this.refreshObjectStoreCallback()}clear(){this.dataGrid.rootNode().removeChildren(),this.entries=[]}updateToolbarEnablement(){const e=!this.dataGrid||0===this.dataGrid.rootNode().children.length;this.deleteSelectedButton.setEnabled(!e&&null!==this.dataGrid.selectedNode)}wasShown(){super.wasShown(),this.registerCSSFiles([vt])}}class Ct extends m.DataGrid.DataGridNode{selectable;valueObjectPresentation;constructor(e){super(e,!1),this.selectable=!0,this.valueObjectPresentation=null}createCell(e){const t=super.createCell(e),i=this.data[e];switch(e){case"value":{t.removeChildren();const e=f.ObjectPropertiesSection.ObjectPropertiesSection.defaultObjectPropertiesSection(i,void 0,!0,!0);t.appendChild(e.element),this.valueObjectPresentation=e;break}case"key":case"primaryKey":{t.removeChildren();const e=f.ObjectPropertiesSection.ObjectPropertiesSection.defaultObjectPresentation(i,void 0,!0,!0);t.appendChild(e);break}}return t}}var Tt,It=Object.freeze({__proto__:null,IDBDatabaseView:kt,IDBDataView:ft,IDBDataGridNode:Ct});class Et extends o.SDKModel.SDKModel{storageAgent;enabled;constructor(e){super(e),e.registerStorageDispatcher(this),this.storageAgent=e.storageAgent(),this.enabled=!1}enable(){this.enabled||this.storageAgent.invoke_setInterestGroupTracking({enable:!0})}disable(){this.enabled&&this.storageAgent.invoke_setInterestGroupTracking({enable:!1})}interestGroupAccessed(e){this.dispatchEventToListeners(Tt.InterestGroupAccess,e)}indexedDBListUpdated(e){}indexedDBContentUpdated(e){}cacheStorageListUpdated(e){}cacheStorageContentUpdated(e){}sharedStorageAccessed(e){}storageBucketCreatedOrUpdated(e){}storageBucketDeleted(e){}}o.SDKModel.SDKModel.register(Et,{capabilities:o.Target.Capability.Storage,autostart:!1}),(Tt||(Tt={})).InterestGroupAccess="InterestGroupAccess";var Mt=Object.freeze({__proto__:null,InterestGroupStorageModel:Et,get Events(){return Tt}});const xt=new CSSStyleSheet;xt.replaceSync("devtools-interest-group-access-grid{overflow:auto}.placeholder{display:flex;align-items:center;justify-content:center;font-size:13px;color:var(--color-text-secondary)}\n/*# sourceURL=interestGroupStorageView.css */\n");const Rt={clickToDisplayBody:"Click on any interest group event to display the group's current state",noDataAvailable:"No details available for the selected interest group. The browser may have left the group."},Lt=i.i18n.registerUIStrings("panels/application/InterestGroupStorageView.ts",Rt),Dt=i.i18n.getLocalizedString.bind(void 0,Lt);class Pt extends l.SplitWidget.SplitWidget{interestGroupGrid=new u.InterestGroupAccessGrid.InterestGroupAccessGrid;events=[];detailsGetter;noDataView;noDisplayView;constructor(e){super(!1,!0),this.detailsGetter=e;const t=new l.Widget.VBox;this.noDisplayView=new l.Widget.VBox,this.noDataView=new l.Widget.VBox,t.setMinimumSize(0,80),this.setMainWidget(t),this.noDisplayView.setMinimumSize(0,40),this.setSidebarWidget(this.noDisplayView),this.noDataView.setMinimumSize(0,40),t.contentElement.appendChild(this.interestGroupGrid),this.interestGroupGrid.addEventListener("cellfocused",this.onFocus.bind(this)),this.noDisplayView.contentElement.classList.add("placeholder");this.noDisplayView.contentElement.createChild("div").textContent=Dt(Rt.clickToDisplayBody),this.noDataView.contentElement.classList.add("placeholder");this.noDataView.contentElement.createChild("div").textContent=Dt(Rt.noDataAvailable)}wasShown(){super.wasShown();const e=this.sidebarWidget();e&&e.registerCSSFiles([xt])}addEvent(e){this.events.find((t=>{return s=e,(i=t).accessTime===s.accessTime&&i.type===s.type&&i.ownerOrigin===s.ownerOrigin&&i.name===s.name;var i,s}))||(this.events.push(e),this.interestGroupGrid.data=this.events)}clearEvents(){this.events=[],this.interestGroupGrid.data=this.events,this.setSidebarWidget(this.noDisplayView)}async onFocus(e){const t=e.data.row;if(!t)return;const i=t.cells.find((e=>"event-group-owner"===e.columnId))?.value,s=t.cells.find((e=>"event-group-name"===e.columnId))?.value;if(!i||!s)return;const r=await this.detailsGetter.getInterestGroupDetails(i,s);if(r){const e=await d.JSONView.JSONView.createView(JSON.stringify(r));e?.setMinimumSize(0,40),e&&this.setSidebarWidget(e)}else this.setSidebarWidget(this.noDataView)}getEventsForTesting(){return this.events}getInterestGroupGridForTesting(){return this.interestGroupGrid}}var Bt=Object.freeze({__proto__:null,InterestGroupStorageView:Pt});const Ft={interestGroups:"Interest Groups"},Vt=i.i18n.registerUIStrings("panels/application/InterestGroupTreeElement.ts",Ft),At=i.i18n.getLocalizedString.bind(void 0,Vt);class Ot extends D{view;constructor(e){super(e,At(Ft.interestGroups),!1);const t=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([t]),this.view=new Pt(this)}get itemURL(){return"interest-groups://"}async getInterestGroupDetails(e,t){const i=o.TargetManager.TargetManager.instance().primaryPageTarget();if(!i)return null;return(await i.storageAgent().invoke_getInterestGroupDetails({ownerOrigin:e,name:t})).details}onselect(e){return super.onselect(e),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.interest_groups]),!1}addEvent(e){this.view.addEvent(e)}clearEvents(){this.view.clearEvents()}}var Wt=Object.freeze({__proto__:null,i18nString:At,InterestGroupTreeElement:Ot});const Ut=new CSSStyleSheet;Ut.replaceSync('.report-content-box{overflow:initial}.report-field-name{flex:0 0 200px}.report-field-value{user-select:text;display:flex}.report-field .inline-name{color:var(--color-text-disabled);padding-left:2ex;user-select:none;white-space:pre-line}.report-field .inline-name::after{content:":\\A0"}.report-field .inline-comment{color:var(--color-text-secondary);padding-left:1ex;white-space:pre-line}.report-field .inline-comment::before{content:"("}.report-field .inline-comment::after{content:")"}.report-field .inline-span{color:var(--color-text-secondary);padding-left:1ex;white-space:pre-line}.report-field-value-link{display:inline-block}.icon-link.devtools-link{background-color:var(--color-link);vertical-align:sub}.frame-details-container{overflow:auto}.frame-details-report-container{min-width:550px}.text-ellipsis{overflow:hidden;text-overflow:ellipsis}\n/*# sourceURL=openedWindowDetailsView.css */\n');const Nt={yes:"Yes",no:"No",clickToRevealInElementsPanel:"Click to reveal in Elements panel",document:"Document",url:"URL",security:"Security",openerFrame:"Opener Frame",accessToOpener:"Access to opener",showsWhetherTheOpenedWindowIs:"Shows whether the opened window is able to access its opener and vice versa",windowWithoutTitle:"Window without title",closed:"closed",worker:"worker",type:"Type",securityIsolation:"Security & Isolation",crossoriginEmbedderPolicy:"Cross-Origin Embedder Policy",webWorker:"Web Worker",unknown:"Unknown",reportingTo:"reporting to"},Ht=i.i18n.registerUIStrings("panels/application/OpenedWindowDetailsView.ts",Nt),_t=i.i18n.getLocalizedString.bind(void 0,Ht);async function Gt(t){let i=null;if(t instanceof o.ResourceTreeModel.ResourceTreeFrame?i=t:t&&(i=o.FrameManager.FrameManager.instance().getFrame(t)),!i)return null;const s=await i.getOwnerDOMNodeOrDocument();if(!s)return null;const r=function(e,t,i){const s=l.Icon.Icon.create(e,"icon-link devtools-link"),r=document.createElement("span");return l.Tooltip.Tooltip.install(r,t),r.classList.add("devtools-link"),r.tabIndex=0,r.appendChild(s),r.addEventListener("click",(e=>{e.consume(!0),i()})),r.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.consume(!0),i())})),r}("code-circle",_t(Nt.clickToRevealInElementsPanel),(()=>e.Revealer.reveal(s))),a=document.createElement("span");return a.textContent=`<${s.nodeName().toLocaleLowerCase()}>`,r.insertBefore(a,r.firstChild),r.addEventListener("mouseenter",(()=>{i&&i.highlight()})),r.addEventListener("mouseleave",(()=>{o.OverlayModel.OverlayModel.hideDOMNodeHighlight()})),r}class qt extends l.ThrottledWidget.ThrottledWidget{targetInfo;isWindowClosed;reportView;documentSection;URLFieldValue;securitySection;openerElementField;hasDOMAccessValue;constructor(e,t){super(),this.targetInfo=e,this.isWindowClosed=t,this.contentElement.classList.add("frame-details-container"),this.reportView=new l.ReportView.ReportView(this.buildTitle()),this.reportView.show(this.contentElement),this.reportView.element.classList.add("frame-details-report-container"),this.documentSection=this.reportView.appendSection(_t(Nt.document)),this.URLFieldValue=this.documentSection.appendField(_t(Nt.url)).createChild("div","text-ellipsis"),this.securitySection=this.reportView.appendSection(_t(Nt.security)),this.openerElementField=this.securitySection.appendField(_t(Nt.openerFrame)),this.securitySection.setFieldVisible(_t(Nt.openerFrame),!1),this.hasDOMAccessValue=this.securitySection.appendField(_t(Nt.accessToOpener)),l.Tooltip.Tooltip.install(this.hasDOMAccessValue,_t(Nt.showsWhetherTheOpenedWindowIs)),this.update()}async doUpdate(){var e;this.reportView.setTitle(this.buildTitle()),this.URLFieldValue.textContent=this.targetInfo.url,this.URLFieldValue.title=this.targetInfo.url,this.hasDOMAccessValue.textContent=(e=this.targetInfo.canAccessOpener,_t(e?Nt.yes:Nt.no)),this.maybeDisplayOpenerFrame()}async maybeDisplayOpenerFrame(){this.openerElementField.removeChildren();const e=await Gt(this.targetInfo.openerFrameId);if(e)return this.openerElementField.append(e),void this.securitySection.setFieldVisible(_t(Nt.openerFrame),!0);this.securitySection.setFieldVisible(_t(Nt.openerFrame),!1)}buildTitle(){let e=this.targetInfo.title||_t(Nt.windowWithoutTitle);return this.isWindowClosed&&(e+=` (${_t(Nt.closed)})`),e}setIsWindowClosed(e){this.isWindowClosed=e}setTargetInfo(e){this.targetInfo=e}wasShown(){super.wasShown(),this.reportView.registerCSSFiles([Ut]),this.registerCSSFiles([Ut])}}class Kt extends l.ThrottledWidget.ThrottledWidget{targetInfo;reportView;documentSection;isolationSection;coepPolicy;constructor(e){super(),this.targetInfo=e,this.contentElement.classList.add("frame-details-container"),this.reportView=new l.ReportView.ReportView(this.targetInfo.title||this.targetInfo.url||_t(Nt.worker)),this.reportView.show(this.contentElement),this.reportView.element.classList.add("frame-details-report-container"),this.documentSection=this.reportView.appendSection(_t(Nt.document));const t=this.documentSection.appendField(_t(Nt.url)).createChild("div","text-ellipsis");t.textContent=this.targetInfo.url,t.title=this.targetInfo.url;this.documentSection.appendField(_t(Nt.type)).textContent=this.workerTypeToString(this.targetInfo.type),this.isolationSection=this.reportView.appendSection(_t(Nt.securityIsolation)),this.coepPolicy=this.isolationSection.appendField(_t(Nt.crossoriginEmbedderPolicy)),this.update()}workerTypeToString(e){return"worker"===e?_t(Nt.webWorker):"service_worker"===e?i.i18n.lockedString("Service Worker"):_t(Nt.unknown)}async updateCoopCoepStatus(){const e=o.TargetManager.TargetManager.instance().targetById(this.targetInfo.targetId);if(!e)return;const t=e.model(o.NetworkManager.NetworkManager),i=t&&await t.getSecurityIsolationStatus(null);if(!i)return;this.fillCrossOriginPolicy(this.coepPolicy,(e=>"None"!==e),i.coep)}fillCrossOriginPolicy(e,t,i){if(!i)return void(e.textContent="");const s=t(i.value);if(e.textContent=s?i.value:i.reportOnlyValue,!s&&t(i.reportOnlyValue)){const t=document.createElement("span");t.classList.add("inline-comment"),t.textContent="report-only",e.appendChild(t)}const r=s?i.reportingEndpoint:i.reportOnlyReportingEndpoint;if(r){e.createChild("span","inline-name").textContent=_t(Nt.reportingTo);e.createChild("span").textContent=r}}async doUpdate(){await this.updateCoopCoepStatus()}wasShown(){super.wasShown(),this.reportView.registerCSSFiles([Ut]),this.registerCSSFiles([Ut])}}var jt=Object.freeze({__proto__:null,OpenedWindowDetailsView:qt,WorkerDetailsView:Kt});const zt=new CSSStyleSheet;zt.replaceSync('.service-worker-version{display:flex;flex-wrap:wrap}.service-worker-version-stack{position:relative}.service-worker-version-stack-bar{position:absolute;top:10px;bottom:20px;left:4px;content:"";border-left:1px solid var(--color-details-hairline);z-index:0}.service-worker-version:not(:last-child){margin-bottom:7px}.service-worker-version-string{flex-shrink:0}.service-worker-active-circle,\n.service-worker-redundant-circle,\n.service-worker-waiting-circle,\n.service-worker-installing-circle{position:relative;display:inline-block;width:10px;height:10px;z-index:10;margin-right:5px;border-radius:50%;border:1px solid var(--color-text-secondary);align-self:center;flex-shrink:0}.service-worker-active-circle{background-color:#50b04f}.service-worker-waiting-circle{background-color:#f38e24}.service-worker-installing-circle{background-color:var(--color-background)}.service-worker-redundant-circle{background-color:#808080}.service-worker-subtitle{padding-left:14px;line-height:14px;color:var(--color-text-disabled)}.link{margin-left:7px}.service-worker-editor-with-button{align-items:baseline;display:flex}.service-worker-notification-editor{border:1px solid var(--color-details-hairline);display:flex;flex:auto;margin-right:4px;max-width:400px;min-width:80px}.report-field-value{white-space:normal}.report-field-value-filename,\n.service-worker-client-string{max-width:400px;overflow:hidden;text-overflow:ellipsis}.report-field-value-filename{padding-left:2px;margin-left:-2px}.report-field-value-subtitle{overflow:hidden;text-overflow:ellipsis}.service-worker-client{display:flex}.service-worker-client-focus-link{flex:none;margin-right:2px;align-self:center}.service-worker-notification-editor.source-code{padding:4px}.service-worker-list{background-color:var(--color-background-elevation-1);overflow:auto}.service-workers-this-origin{flex-shrink:0;flex-grow:0}.service-workers-this-origin,\n.service-workers-other-origin{min-width:530px}.service-worker-has-current .service-workers-other-origin{margin-top:16px;border-top:1px solid var(--color-details-hairline)}.devtools-link{line-height:14px;align-self:center;padding:1px}button.link{padding:1px}button.link:focus-visible{background-color:inherit}\n/*# sourceURL=serviceWorkersView.css */\n');const Qt=new CSSStyleSheet;Qt.replaceSync('.resource-service-worker-update-view{display:block;margin:6px;color:rgb(30% 30% 30%);overflow:auto}.service-worker-update-timing-table{border:1px solid var(--color-details-hairline);border-spacing:0;padding-left:10px;padding-right:10px;line-height:initial;table-layout:auto;overflow:hidden}.service-worker-update-timing-row{position:relative;height:20px;overflow:hidden;min-width:80px}.service-worker-update-timing-bar{position:absolute;min-width:1px;top:0;bottom:0}.service-worker-update-timing-bar-clickable::before{user-select:none;-webkit-mask-image:var(--image-file-triangle-right);float:left;width:14px;height:14px;margin-right:2px;content:"";position:relative;background-color:var(--icon-default);transition:transform 200ms}.service-worker-update-timing-bar-clickable{position:relative;left:-12px}.service-worker-update-timing-bar-clickable:focus-visible{background-color:var(--color-background-elevation-1)}.service-worker-update-timing-bar-clickable[aria-checked="true"]::before{transform:rotate(90deg)}.service-worker-update-timing-bar-details-collapsed{display:none}.service-worker-update-timing-bar-details-expanded{display:table-row}.service-worker-update-timing-bar-details:focus-visible{background-color:var(--legacy-selection-bg-color)}.service-worker-update-timing-bar.activate{top:5px;height:10px;background-color:#ff9800}.service-worker-update-timing-bar.wait{top:5px;height:10px;background-color:#9c27b0}.service-worker-update-timing-bar.install{top:5px;height:10px;background-color:#009688}.service-worker-update-timing-table > tr > td{padding:4px 0;padding-right:10px}table.service-worker-update-timing-table > tr.service-worker-update-timing-table-header > td{border-top:5px solid transparent;color:#737373}table.service-worker-update-timing-table > tr.service-worker-update-timing-bar-details > td:first-child{padding-left:12px}table.service-worker-update-timing-table > tr.service-worker-update-timeline > td:first-child{padding-left:12px}\n/*# sourceURL=serviceWorkerUpdateCycleView.css */\n');const $t={version:"Version",updateActivity:"Update Activity",timeline:"Timeline",startTimeS:"Start time: {PH1}",endTimeS:"End time: {PH1}"},Jt=i.i18n.registerUIStrings("panels/application/ServiceWorkerUpdateCycleView.ts",$t),Xt=i.i18n.getLocalizedString.bind(void 0,Jt);class Yt{registration;rows;selectedRowIndex;tableElement;constructor(e){this.registration=e,this.rows=[],this.selectedRowIndex=-1,this.tableElement=document.createElement("table"),this.createTimingTable()}calculateServiceWorkerUpdateRanges(){function e(e,t){t.start<Number.MAX_VALUE&&t.start<=t.end&&e.push(t)}function t(t){let i=t.currentState,s=0,r=0,a=0,o=0;const n=i.status;if("new"===n)return[];for(;i;)"activated"===i.status?s=i.last_updated_timestamp:"activating"===i.status?(0===s&&(s=i.last_updated_timestamp),r=i.last_updated_timestamp):"installed"===i.status?a=i.last_updated_timestamp:"installing"===i.status&&(0===a&&(a=i.last_updated_timestamp),o=i.last_updated_timestamp),i=i.previousState;const d=[];return function(t,i,s,r,a,o,n){e(t,{id:i,phase:"Install",start:s,end:r}),"activating"!==n&&"activated"!==n&&"redundant"!==n||(e(t,{id:i,phase:"Wait",start:r,end:a}),e(t,{id:i,phase:"Activate",start:a,end:o}))}(d,t.id,o,a,r,s,n),d}const i=this.registration.versionsByMode(),s=[o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Active,o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Waiting,o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Installing,o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Redundant];for(const e of s){const s=i.get(e);if(s){return t(s)}}return[]}createTimingTable(){this.tableElement.classList.add("service-worker-update-timing-table");const e=this.calculateServiceWorkerUpdateRanges();this.updateTimingTable(e)}createTimingTableHead(){const e=this.tableElement.createChild("tr","service-worker-update-timing-table-header");l.UIUtils.createTextChild(e.createChild("td"),Xt($t.version)),l.UIUtils.createTextChild(e.createChild("td"),Xt($t.updateActivity)),l.UIUtils.createTextChild(e.createChild("td"),Xt($t.timeline))}removeRows(){const e=this.tableElement.getElementsByTagName("tr");for(;e[0];)e[0].parentNode&&e[0].parentNode.removeChild(e[0]);this.rows=[]}updateTimingTable(e){this.selectedRowIndex=-1,this.removeRows(),this.createTimingTableHead();const t=e;if(0===t.length)return;const i=t.map((e=>e.start)),s=t.map((e=>e.end)),r=i.reduce(((e,t)=>Math.min(e,t))),a=s.reduce(((e,t)=>Math.max(e,t))),o=100/(a-r);for(const e of t){const t=e.phase,i=o*(e.start-r),s=o*(a-e.end),n=this.tableElement.createChild("tr","service-worker-update-timeline");this.rows.push(n);const d=n.createChild("td");l.UIUtils.createTextChild(d,"#"+e.id),d.classList.add("service-worker-update-timing-bar-clickable"),d.setAttribute("tabindex","0"),d.setAttribute("role","switch"),d.addEventListener("focus",(e=>{this.onFocus(e)})),l.ARIAUtils.setChecked(d,!1);const c=n.createChild("td");l.UIUtils.createTextChild(c,t);const h=n.createChild("td").createChild("div","service-worker-update-timing-row").createChild("span","service-worker-update-timing-bar "+t.toLowerCase());h.style.left=i+"%",h.style.right=s+"%",h.textContent="​",this.constructUpdateDetails(n,e)}}constructUpdateDetails(e,t){const i=this.tableElement.createChild("tr","service-worker-update-timing-bar-details");i.classList.add("service-worker-update-timing-bar-details-collapsed");const s=i.createChild("td");s.colSpan=3;const r=new Date(t.start).toISOString();l.UIUtils.createTextChild(s.createChild("span"),Xt($t.startTimeS,{PH1:r})),i.tabIndex=0;const a=this.tableElement.createChild("tr","service-worker-update-timing-bar-details");a.classList.add("service-worker-update-timing-bar-details-collapsed");const o=a.createChild("td");o.colSpan=3;const n=new Date(t.end).toISOString();l.UIUtils.createTextChild(o.createChild("span"),Xt($t.endTimeS,{PH1:n})),a.tabIndex=0,e.addEventListener("keydown",(e=>{this.onKeydown(e,i,a)})),e.addEventListener("click",(e=>{this.onClick(e,i,a)}))}toggle(e,t,i,s){i.classList.contains("service-worker-update-timing-bar-clickable")&&(e.classList.toggle("service-worker-update-timing-bar-details-collapsed"),e.classList.toggle("service-worker-update-timing-bar-details-expanded"),t.classList.toggle("service-worker-update-timing-bar-details-collapsed"),t.classList.toggle("service-worker-update-timing-bar-details-expanded"),l.ARIAUtils.setChecked(i,!s))}onFocus(e){const t=e.target;if(!t)return;const i=t.parentElement;i&&(this.selectedRowIndex=this.rows.indexOf(i))}onKeydown(e,t,i){if(!e.target)return;const s=e.target,r=e,a="true"===s.getAttribute("aria-checked");return"Enter"===r.key||" "===r.key||!a&&"ArrowRight"===r.key||a&&"ArrowLeft"===r.key?(this.toggle(t,i,s,a),void e.preventDefault()):("ArrowDown"===r.key&&(this.selectedRowIndex>=0?this.selectNextRow():this.selectFirstRow(),e.preventDefault()),void("ArrowUp"===r.key&&(this.selectedRowIndex>=0?this.selectPreviousRow():this.selectLastRow(),e.preventDefault())))}focusRow(e){e.cells[0].focus()}blurRow(e){e.cells[0].blur()}selectFirstRow(){0!==this.rows.length&&(this.selectedRowIndex=0,this.focusRow(this.rows[0]))}selectLastRow(){0!==this.rows.length&&(this.selectedRowIndex=this.rows.length-1,this.focusRow(this.rows[this.selectedRowIndex]))}selectNextRow(){if(0===this.rows.length)return;const e=this.selectedRowIndex;this.selectedRowIndex++,this.selectedRowIndex>=this.rows.length&&(this.selectedRowIndex=0),this.blurRow(this.rows[e]),this.focusRow(this.rows[this.selectedRowIndex])}selectPreviousRow(){if(0===this.rows.length)return;const e=this.selectedRowIndex;this.selectedRowIndex--,this.selectedRowIndex<0&&(this.selectedRowIndex=this.rows.length-1),this.blurRow(this.rows[e]),this.focusRow(this.rows[this.selectedRowIndex])}onClick(e,t,i){const s=e.target;if(!s)return;const r="true"===s.getAttribute("aria-checked");this.toggle(t,i,s,r),e.preventDefault()}refresh(){const e=this.calculateServiceWorkerUpdateRanges();this.updateTimingTable(e)}}var Zt=Object.freeze({__proto__:null,ServiceWorkerUpdateCycleView:Yt});const ei={serviceWorkersFromOtherOrigins:"Service workers from other origins",updateOnReload:"Update on reload",onPageReloadForceTheService:"On page reload, force the `service worker` to update, and activate it",bypassForNetwork:"Bypass for network",bypassTheServiceWorkerAndLoad:"Bypass the `service worker` and load resources from the network",serviceWorkerForS:"`Service worker` for {PH1}",testPushMessageFromDevtools:"Test push message from DevTools.",networkRequests:"Network requests",update:"Update",unregisterServiceWorker:"Unregister service worker",unregister:"Unregister",source:"Source",status:"Status",clients:"Clients",pushString:"Push",pushData:"Push data",syncString:"Sync",syncTag:"Sync tag",periodicSync:"Periodic Sync",periodicSyncTag:"Periodic Sync tag",sRegistrationErrors:"{PH1} registration errors",receivedS:"Received {PH1}",sDeleted:"{PH1} - deleted",sActivatedAndIsS:"#{PH1} activated and is {PH2}",stopString:"stop",inspect:"inspect",startString:"start",sIsRedundant:"#{PH1} is redundant",sWaitingToActivate:"#{PH1} waiting to activate",sTryingToInstall:"#{PH1} trying to install",updateCycle:"Update Cycle",workerS:"Worker: {PH1}",focus:"focus",seeAllRegistrations:"See all registrations"},ti=i.i18n.registerUIStrings("panels/application/ServiceWorkersView.ts",ei),ii=i.i18n.getLocalizedString.bind(void 0,ti);let si=!1;class ri extends l.Widget.VBox{currentWorkersView;toolbar;sections;manager;securityOriginManager;sectionToRegistration;eventListeners;constructor(){super(!0),this.currentWorkersView=new l.ReportView.ReportView(i.i18n.lockedString("Service Workers")),this.currentWorkersView.setBodyScrollable(!1),this.contentElement.classList.add("service-worker-list"),this.currentWorkersView.show(this.contentElement),this.currentWorkersView.element.classList.add("service-workers-this-origin"),this.toolbar=this.currentWorkersView.createToolbar(),this.toolbar.makeWrappable(!0),this.sections=new Map,this.manager=null,this.securityOriginManager=null,this.sectionToRegistration=new WeakMap;const s=this.contentElement.createChild("div","service-workers-other-origin"),r=new l.ReportView.ReportView;r.setHeaderVisible(!1),r.show(s);const a=r.appendSection(ii(ei.serviceWorkersFromOtherOrigins)).appendRow(),n=l.Fragment.html`<a class="devtools-link" role="link" tabindex="0" href="chrome://serviceworker-internals" target="_blank" style="display: inline; cursor: pointer;">${ii(ei.seeAllRegistrations)}</a>`;self.onInvokeElement(n,(e=>{const t=o.TargetManager.TargetManager.instance().rootTarget();t&&t.targetAgent().invoke_createTarget({url:"chrome://serviceworker-internals?devtools"}),e.consume(!0)})),a.appendChild(n),this.toolbar.appendToolbarItem(I.ThrottlingManager.throttlingManager().createOfflineToolbarCheckbox());const d=e.Settings.Settings.instance().createSetting("serviceWorkerUpdateOnReload",!1);d.setTitle(ii(ei.updateOnReload));const c=new l.Toolbar.ToolbarSettingCheckbox(d,ii(ei.onPageReloadForceTheService));this.toolbar.appendToolbarItem(c);const h=e.Settings.Settings.instance().createSetting("bypassServiceWorker",!1);h.setTitle(ii(ei.bypassForNetwork));const g=new l.Toolbar.ToolbarSettingCheckbox(h,ii(ei.bypassTheServiceWorkerAndLoad));this.toolbar.appendToolbarItem(g),this.eventListeners=new Map,o.TargetManager.TargetManager.instance().observeModels(o.ServiceWorkerManager.ServiceWorkerManager,this),this.updateListVisibility();document.body.addEventListener(l.InspectorView.Events.DrawerChange,(i=>{const s=i.detail&&i.detail.isDrawerOpen;if(this.manager&&!s){const{serviceWorkerNetworkRequestsPanelStatus:{isOpen:i,openedAt:s}}=this.manager;if(i){const i=l.ViewManager.ViewManager.instance().locationNameForViewId("network");l.ViewManager.ViewManager.instance().showViewInLocation("network",i,!1),e.Revealer.reveal(E.UIFilter.UIRequestFilter.filters([]));Date.now()-s<2e3&&t.userMetrics.actionTaken(t.UserMetrics.Action.ServiceWorkerNetworkRequestClosedQuickly),this.manager.serviceWorkerNetworkRequestsPanelStatus={isOpen:!1,openedAt:0}}}}))}modelAdded(e){if(e.target()===o.TargetManager.TargetManager.instance().primaryPageTarget()){this.manager=e,this.securityOriginManager=e.target().model(o.SecurityOriginManager.SecurityOriginManager);for(const e of this.manager.registrations().values())this.updateRegistration(e);this.eventListeners.set(e,[this.manager.addEventListener(o.ServiceWorkerManager.Events.RegistrationUpdated,this.registrationUpdated,this),this.manager.addEventListener(o.ServiceWorkerManager.Events.RegistrationDeleted,this.registrationDeleted,this),this.securityOriginManager.addEventListener(o.SecurityOriginManager.Events.SecurityOriginAdded,this.updateSectionVisibility,this),this.securityOriginManager.addEventListener(o.SecurityOriginManager.Events.SecurityOriginRemoved,this.updateSectionVisibility,this)])}}modelRemoved(t){this.manager&&this.manager===t&&(e.EventTarget.removeEventListeners(this.eventListeners.get(t)||[]),this.eventListeners.delete(t),this.manager=null,this.securityOriginManager=null)}getTimeStamp(e){const t=e.versionsByMode();let i=0;const s=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Active),r=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Installing),a=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Waiting),n=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Redundant);return s?i=s.scriptResponseTime:a?i=a.scriptResponseTime:r?i=r.scriptResponseTime:n&&(i=n.scriptResponseTime),i||0}updateSectionVisibility(){let e=!1;const t=[];for(const i of this.sections.values()){const s=this.getReportViewForOrigin(i.registration.securityOrigin);e=e||s===this.currentWorkersView,i.section.parentWidget()!==s&&t.push(i)}for(const e of t){const t=e.registration;this.removeRegistrationFromList(t),this.updateRegistration(t,!0)}this.currentWorkersView.sortSections(((e,t)=>{const i=this.sectionToRegistration.get(e),s=this.sectionToRegistration.get(t),r=i?this.getTimeStamp(i):0;return(s?this.getTimeStamp(s):0)-r}));for(const e of this.sections.values())e.section.parentWidget()===this.currentWorkersView||this.isRegistrationVisible(e.registration)?e.section.showWidget():e.section.hideWidget();this.contentElement.classList.toggle("service-worker-has-current",Boolean(e)),this.updateListVisibility()}registrationUpdated(e){this.updateRegistration(e.data),this.gcRegistrations()}gcRegistrations(){if(!this.manager||!this.securityOriginManager)return;let e=!1;const t=new Set(this.securityOriginManager.securityOrigins());for(const i of this.manager.registrations().values())if((t.has(i.securityOrigin)||this.isRegistrationVisible(i))&&!i.canBeRemoved()){e=!0;break}if(e)for(const e of this.manager.registrations().values()){!(t.has(e.securityOrigin)||this.isRegistrationVisible(e))&&e.canBeRemoved()&&this.removeRegistrationFromList(e)}}getReportViewForOrigin(e){return this.securityOriginManager&&(this.securityOriginManager.securityOrigins().includes(e)||this.securityOriginManager.unreachableMainSecurityOrigin()===e)?this.currentWorkersView:null}updateRegistration(e,t){let i=this.sections.get(e);if(!i){const t=e.scopeURL,s=this.getReportViewForOrigin(e.securityOrigin);if(!s)return;const r=s.appendSection(t);r.setUiGroupTitle(ii(ei.serviceWorkerForS,{PH1:t})),this.sectionToRegistration.set(r,e),i=new ai(this.manager,r,e),this.sections.set(e,i)}t||(this.updateSectionVisibility(),i.scheduleUpdate())}registrationDeleted(e){this.removeRegistrationFromList(e.data)}removeRegistrationFromList(e){const t=this.sections.get(e);t&&t.section.detach(),this.sections.delete(e),this.updateSectionVisibility()}isRegistrationVisible(e){return!e.scopeURL}updateListVisibility(){this.contentElement.classList.toggle("service-worker-list-empty",0===this.sections.size)}wasShown(){super.wasShown(),this.registerCSSFiles([zt])}}class ai{manager;section;registration;fingerprint;pushNotificationDataSetting;syncTagNameSetting;periodicSyncTagNameSetting;toolbar;updateCycleView;networkRequests;updateButton;deleteButton;sourceField;statusField;clientsField;linkifier;clientInfoCache;throttler;updateCycleField;constructor(t,i,s){this.manager=t,this.section=i,this.registration=s,this.fingerprint=null,this.pushNotificationDataSetting=e.Settings.Settings.instance().createLocalSetting("pushData",ii(ei.testPushMessageFromDevtools)),this.syncTagNameSetting=e.Settings.Settings.instance().createLocalSetting("syncTagName","test-tag-from-devtools"),this.periodicSyncTagNameSetting=e.Settings.Settings.instance().createLocalSetting("periodicSyncTagName","test-tag-from-devtools"),this.toolbar=i.createToolbar(),this.toolbar.renderAsLinks(),this.updateCycleView=new Yt(s),this.networkRequests=new l.Toolbar.ToolbarButton(ii(ei.networkRequests),void 0,ii(ei.networkRequests)),this.networkRequests.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.networkRequestsClicked,this),this.toolbar.appendToolbarItem(this.networkRequests),this.updateButton=new l.Toolbar.ToolbarButton(ii(ei.update),void 0,ii(ei.update)),this.updateButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.updateButtonClicked,this),this.toolbar.appendToolbarItem(this.updateButton),this.deleteButton=new l.Toolbar.ToolbarButton(ii(ei.unregisterServiceWorker),void 0,ii(ei.unregister)),this.deleteButton.addEventListener(l.Toolbar.ToolbarButton.Events.Click,this.unregisterButtonClicked,this),this.toolbar.appendToolbarItem(this.deleteButton),this.sourceField=this.wrapWidget(this.section.appendField(ii(ei.source))),this.statusField=this.wrapWidget(this.section.appendField(ii(ei.status))),this.clientsField=this.wrapWidget(this.section.appendField(ii(ei.clients))),this.createSyncNotificationField(ii(ei.pushString),this.pushNotificationDataSetting.get(),ii(ei.pushData),this.push.bind(this)),this.createSyncNotificationField(ii(ei.syncString),this.syncTagNameSetting.get(),ii(ei.syncTag),this.sync.bind(this)),this.createSyncNotificationField(ii(ei.periodicSync),this.periodicSyncTagNameSetting.get(),ii(ei.periodicSyncTag),(e=>this.periodicSync(e))),this.createUpdateCycleField(),this.linkifier=new h.Linkifier.Linkifier,this.clientInfoCache=new Map,this.throttler=new e.Throttler.Throttler(500)}createSyncNotificationField(e,t,i,s){const r=this.wrapWidget(this.section.appendField(e)).createChild("form","service-worker-editor-with-button"),a=l.UIUtils.createInput("source-code service-worker-notification-editor");r.appendChild(a);const o=l.UIUtils.createTextButton(e);o.type="submit",r.appendChild(o),a.value=t,a.placeholder=i,l.ARIAUtils.setLabel(a,e),r.addEventListener("submit",(e=>{s(a.value||""),e.consume(!0)}))}scheduleUpdate(){si?this.update():this.throttler.schedule(this.update.bind(this))}targetForVersionId(e){const t=this.manager.findVersion(e);return t&&t.targetId?o.TargetManager.TargetManager.instance().targetById(t.targetId):null}addVersion(e,t,i){const s=e.createChild("div","service-worker-version");s.createChild("div",t);const r=s.createChild("span","service-worker-version-string");return r.textContent=i,l.ARIAUtils.markAsAlert(r),s}updateClientsField(e){this.clientsField.removeChildren(),this.section.setFieldVisible(ii(ei.clients),Boolean(e.controlledClients.length));for(const t of e.controlledClients){const e=this.clientsField.createChild("div","service-worker-client"),i=this.clientInfoCache.get(t);i&&this.updateClientInfo(e,i),this.manager.target().targetAgent().invoke_getTargetInfo({targetId:t}).then(this.onClientInfo.bind(this,e))}}updateSourceField(t){this.sourceField.removeChildren();const i=e.ParsedURL.ParsedURL.extractName(t.scriptURL),s=this.sourceField.createChild("div","report-field-value-filename"),r=h.Linkifier.Linkifier.linkifyURL(t.scriptURL,{text:i});if(r.tabIndex=0,s.appendChild(r),this.registration.errors.length){const t=l.UIUtils.createIconLabel({title:String(this.registration.errors.length),iconName:"cross-circle-filled",color:"var(--icon-error)"});t.classList.add("devtools-link","link"),t.tabIndex=0,l.ARIAUtils.setLabel(t,ii(ei.sRegistrationErrors,{PH1:this.registration.errors.length})),self.onInvokeElement(t,(()=>e.Console.Console.instance().show())),s.appendChild(t)}void 0!==t.scriptResponseTime&&(this.sourceField.createChild("div","report-field-value-subtitle").textContent=ii(ei.receivedS,{PH1:new Date(1e3*t.scriptResponseTime).toLocaleString()}))}update(){const e=this.registration.fingerprint();if(e===this.fingerprint)return Promise.resolve();this.fingerprint=e,this.toolbar.setEnabled(!this.registration.isDeleted);const t=this.registration.versionsByMode(),s=this.registration.scopeURL,r=this.registration.isDeleted?ii(ei.sDeleted,{PH1:s}):s;this.section.setTitle(r);const a=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Active),n=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Waiting),d=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Installing),l=t.get(o.ServiceWorkerManager.ServiceWorkerVersion.Modes.Redundant);this.statusField.removeChildren();const c=this.statusField.createChild("div","service-worker-version-stack");if(c.createChild("div","service-worker-version-stack-bar"),a){this.updateSourceField(a);const e=o.ServiceWorkerManager.ServiceWorkerVersion.RunningStatus[a.currentState.runningStatus](),t=this.addVersion(c,"service-worker-active-circle",ii(ei.sActivatedAndIsS,{PH1:a.id,PH2:e}));a.isRunning()||a.isStarting()?(this.createLink(t,ii(ei.stopString),this.stopButtonClicked.bind(this,a.id)),this.targetForVersionId(a.id)||this.createLink(t,ii(ei.inspect),this.inspectButtonClicked.bind(this,a.id))):a.isStartable()&&this.createLink(t,ii(ei.startString),this.startButtonClicked.bind(this)),this.updateClientsField(a)}else l&&(this.updateSourceField(l),this.addVersion(c,"service-worker-redundant-circle",ii(ei.sIsRedundant,{PH1:l.id})),this.updateClientsField(l));if(n){const e=this.addVersion(c,"service-worker-waiting-circle",ii(ei.sWaitingToActivate,{PH1:n.id}));this.createLink(e,i.i18n.lockedString("skipWaiting"),this.skipButtonClicked.bind(this)),void 0!==n.scriptResponseTime&&(e.createChild("div","service-worker-subtitle").textContent=ii(ei.receivedS,{PH1:new Date(1e3*n.scriptResponseTime).toLocaleString()})),this.targetForVersionId(n.id)||!n.isRunning()&&!n.isStarting()||this.createLink(e,ii(ei.inspect),this.inspectButtonClicked.bind(this,n.id))}if(d){const e=this.addVersion(c,"service-worker-installing-circle",ii(ei.sTryingToInstall,{PH1:d.id}));void 0!==d.scriptResponseTime&&(e.createChild("div","service-worker-subtitle").textContent=ii(ei.receivedS,{PH1:new Date(1e3*d.scriptResponseTime).toLocaleString()})),this.targetForVersionId(d.id)||!d.isRunning()&&!d.isStarting()||this.createLink(e,ii(ei.inspect),this.inspectButtonClicked.bind(this,d.id))}return this.updateCycleView.refresh(),Promise.resolve()}createLink(e,t,i,s,r){const a=document.createElement("button");return s&&(a.className=s),a.classList.add("link","devtools-link"),a.textContent=t,a.tabIndex=0,a.addEventListener("click",i,r),e.appendChild(a),a}unregisterButtonClicked(){this.manager.deleteRegistration(this.registration.id)}createUpdateCycleField(){this.updateCycleField=this.wrapWidget(this.section.appendField(ii(ei.updateCycle))),this.updateCycleField.appendChild(this.updateCycleView.tableElement)}updateButtonClicked(){this.manager.updateRegistration(this.registration.id)}networkRequestsClicked(){const i="drawer-view"===l.ViewManager.ViewManager.instance().locationNameForViewId("resources")?"panel":"drawer-view";l.ViewManager.ViewManager.instance().showViewInLocation("network",i),e.Revealer.reveal(E.UIFilter.UIRequestFilter.filters([{filterType:E.UIFilter.FilterType.Is,filterValue:E.UIFilter.IsFilterType.ServiceWorkerIntercepted}]));const s=T.NetworkLog.NetworkLog.instance().requests();let r=null;if(Array.isArray(s))for(const e of s)!r&&e.fetchedViaServiceWorker&&(r=e),e.fetchedViaServiceWorker&&r&&r.responseReceivedTime<e.responseReceivedTime&&(r=e);if(r){const t=E.UIRequestLocation.UIRequestLocation.tab(r,E.UIRequestLocation.UIRequestTabs.Timing,{clearFilter:!1});e.Revealer.reveal(t)}this.manager.serviceWorkerNetworkRequestsPanelStatus={isOpen:!0,openedAt:Date.now()},t.userMetrics.actionTaken(t.UserMetrics.Action.ServiceWorkerNetworkRequestClicked)}push(e){this.pushNotificationDataSetting.set(e),this.manager.deliverPushMessage(this.registration.id,e)}sync(e){this.syncTagNameSetting.set(e),this.manager.dispatchSyncEvent(this.registration.id,e,!0)}periodicSync(e){this.periodicSyncTagNameSetting.set(e),this.manager.dispatchPeriodicSyncEvent(this.registration.id,e)}onClientInfo(e,t){const i=t.targetInfo;i&&(this.clientInfoCache.set(i.targetId,i),this.updateClientInfo(e,i))}updateClientInfo(e,t){if("page"!==t.type&&"iframe"===t.type){const i=e.createChild("span","service-worker-client-string");return void l.UIUtils.createTextChild(i,ii(ei.workerS,{PH1:t.url}))}e.removeChildren();const i=e.createChild("span","service-worker-client-string");l.UIUtils.createTextChild(i,t.url),this.createLink(e,ii(ei.focus),this.activateTarget.bind(this,t.targetId),"service-worker-client-focus-link")}activateTarget(e){this.manager.target().targetAgent().invoke_activateTarget({targetId:e})}startButtonClicked(){this.manager.startWorker(this.registration.scopeURL)}skipButtonClicked(){this.manager.skipWaiting(this.registration.scopeURL)}stopButtonClicked(e){this.manager.stopWorker(e)}inspectButtonClicked(e){this.manager.inspectWorker(e)}wrapWidget(e){const t=l.Utils.createShadowRootWithCoreStyles(e,{cssFile:[zt,Qt],delegatesFocus:void 0}),i=document.createElement("div");return t.appendChild(i),i}}var oi=Object.freeze({__proto__:null,setThrottleDisabledForDebugging:e=>{si=e},ServiceWorkersView:ri,Section:ai});const ni=new CSSStyleSheet;ni.replaceSync("devtools-shared-storage-access-grid{overflow:auto}.placeholder{display:flex;align-items:center;justify-content:center;font-size:13px;color:var(--color-text-secondary)}\n/*# sourceURL=sharedStorageEventsView.css */\n");const di={clickToDisplayBody:"Click on any shared storage event to display the event parameters."},li=i.i18n.registerUIStrings("panels/application/SharedStorageEventsView.ts",di),ci=i.i18n.getLocalizedString.bind(void 0,li);class hi extends l.SplitWidget.SplitWidget{#t=new u.SharedStorageAccessGrid.SharedStorageAccessGrid;#i=[];#s;#r="";constructor(){super(!1,!0);const e=new l.Widget.VBox;this.#s=new l.Widget.VBox,e.setMinimumSize(0,80),this.setMainWidget(e),this.#s.setMinimumSize(0,40),this.setSidebarWidget(this.#s),e.contentElement.appendChild(this.#t),this.#t.addEventListener("cellfocused",this.#a.bind(this)),this.#o()?.addEventListener(o.ResourceTreeModel.Events.PrimaryPageChanged,this.clearEvents,this),this.#s.contentElement.classList.add("placeholder");this.#s.contentElement.createChild("div").textContent=ci(di.clickToDisplayBody)}#o(){return o.TargetManager.TargetManager.instance().primaryPageTarget()?.model(o.ResourceTreeModel.ResourceTreeModel)||null}#n(){return this.#o()?.mainFrame||null}get id(){return this.#n()?.id||this.#r}wasShown(){super.wasShown();const e=this.sidebarWidget();e&&e.registerCSSFiles([ni])}addEvent(e){e.mainFrameId===this.id&&(this.#i.some((t=>{return i=t,s=e,JSON.stringify(i)===JSON.stringify(s);var i,s}))||(this.#i.push(e),this.#t.data=this.#i))}clearEvents(){this.#i=[],this.#t.data=this.#i,this.setSidebarWidget(this.#s)}async#a(e){const t=e.data.row;if(!t)return;const i={accessTime:t.cells.find((e=>"event-time"===e.columnId))?.value,accessType:t.cells.find((e=>"event-type"===e.columnId))?.value,ownerOrigin:t.cells.find((e=>"event-owner-origin"===e.columnId))?.value,eventParams:JSON.parse(t.cells.find((e=>"event-params"===e.columnId))?.value)},s=d.JSONView.JSONView.createViewSync(i);s.setMinimumSize(0,40),this.setSidebarWidget(s)}setDefaultIdForTesting(e){this.#r=e}getEventsForTesting(){return this.#i}getSharedStorageAccessGridForTesting(){return this.#t}}var gi=Object.freeze({__proto__:null,SharedStorageEventsView:hi});const ui={sharedStorage:"Shared Storage"},pi=i.i18n.registerUIStrings("panels/application/SharedStorageListTreeElement.ts",ui),mi=i.i18n.getLocalizedString.bind(void 0,pi);class wi extends D{#d;view;constructor(t,i=!1){super(t,mi(ui.sharedStorage),!1),this.#d=e.Settings.Settings.instance().createSetting("resourcesSharedStorageExpanded",i);const s=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([s]),this.view=new hi}get itemURL(){return"shared-storage://"}onselect(e){return super.onselect(e),this.resourcesPanel.showView(this.view),!1}onattach(){super.onattach(),this.#d.get()&&this.expand()}onexpand(){this.#d.set(!0)}oncollapse(){this.#d.set(!1)}addEvent(e){this.view.addEvent(e)}}var vi,Si=Object.freeze({__proto__:null,SharedStorageListTreeElement:wi});class bi extends e.ObjectWrapper.ObjectWrapper{#l;#c;constructor(e,t){super(),this.#l=e,this.#c=t}get securityOrigin(){return this.#c}async getMetadata(){return this.#l.storageAgent.invoke_getSharedStorageMetadata({ownerOrigin:this.securityOrigin}).then((({metadata:e})=>e))}async getEntries(){return this.#l.storageAgent.invoke_getSharedStorageEntries({ownerOrigin:this.securityOrigin}).then((({entries:e})=>e))}async setEntry(e,t,i){await this.#l.storageAgent.invoke_setSharedStorageEntry({ownerOrigin:this.securityOrigin,key:e,value:t,ignoreIfPresent:i})}async deleteEntry(e){await this.#l.storageAgent.invoke_deleteSharedStorageEntry({ownerOrigin:this.securityOrigin,key:e})}async clear(){await this.#l.storageAgent.invoke_clearSharedStorageEntries({ownerOrigin:this.securityOrigin})}async resetBudget(){await this.#l.storageAgent.invoke_resetSharedStorageBudget({ownerOrigin:this.securityOrigin})}}!function(e){let t;!function(e){e.SharedStorageChanged="SharedStorageChanged"}(t=e.Events||(e.Events={}))}(bi||(bi={}));class yi extends o.SDKModel.SDKModel{#h;#g;storageAgent;#u;constructor(e){super(e),e.registerStorageDispatcher(this),this.#h=e.model(o.SecurityOriginManager.SecurityOriginManager),this.#g=new Map,this.storageAgent=e.storageAgent(),this.#u=!1}async enable(){this.#u||(this.#h.addEventListener(o.SecurityOriginManager.Events.SecurityOriginAdded,this.#p,this),this.#h.addEventListener(o.SecurityOriginManager.Events.SecurityOriginRemoved,this.#m,this),await this.storageAgent.invoke_setSharedStorageTracking({enable:!0}),this.#w(),this.#u=!0)}disable(){this.#u&&(this.#h.removeEventListener(o.SecurityOriginManager.Events.SecurityOriginAdded,this.#p,this),this.#h.removeEventListener(o.SecurityOriginManager.Events.SecurityOriginRemoved,this.#m,this),this.storageAgent.invoke_setSharedStorageTracking({enable:!1}),this.#v(),this.#u=!1)}dispose(){this.disable()}#w(){for(const e of this.#h.securityOrigins())this.#S(e)}#v(){for(const e of this.#g.keys())this.#b(e)}#p(e){this.#S(e.data)}#S(t){const i=new e.ParsedURL.ParsedURL(t);if(!i.isValid||"data"===i.scheme||"about"===i.scheme||"javascript"===i.scheme)return;if(this.#g.has(t))return;const s=new bi(this,t);this.#g.set(t,s),this.dispatchEventToListeners(vi.SharedStorageAdded,s)}#m(e){this.#b(e.data)}#b(e){const t=this.storageForOrigin(e);t&&(this.#g.delete(e),this.dispatchEventToListeners(vi.SharedStorageRemoved,t))}storages(){return this.#g.values()}storageForOrigin(e){return this.#g.get(e)||null}numStoragesForTesting(){return this.#g.size}isChangeEvent(e){return["documentSet","documentAppend","documentDelete","documentClear","workletSet","workletAppend","workletDelete","workletClear"].includes(e.type)}sharedStorageAccessed(e){if(this.isChangeEvent(e)){const t=this.storageForOrigin(e.ownerOrigin);if(t){const i={accessTime:e.accessTime,type:e.type,mainFrameId:e.mainFrameId,params:e.params};t.dispatchEventToListeners(bi.Events.SharedStorageChanged,i)}else this.#S(e.ownerOrigin)}this.dispatchEventToListeners(vi.SharedStorageAccess,e)}indexedDBListUpdated(e){}indexedDBContentUpdated(e){}cacheStorageListUpdated(e){}cacheStorageContentUpdated(e){}interestGroupAccessed(e){}storageBucketCreatedOrUpdated(e){}storageBucketDeleted(e){}}o.SDKModel.SDKModel.register(yi,{capabilities:o.Target.Capability.Storage,autostart:!1}),function(e){e.SharedStorageAccess="SharedStorageAccess",e.SharedStorageAdded="SharedStorageAdded",e.SharedStorageRemoved="SharedStorageRemoved"}(vi||(vi={}));var ki=Object.freeze({__proto__:null,get SharedStorageForOrigin(){return bi},SharedStorageModel:yi,get Events(){return vi}});const fi={refresh:"Refresh",filter:"Filter",clearAll:"Clear All",deleteSelected:"Delete Selected",refreshedStatus:"Table refreshed"},Ci=i.i18n.registerUIStrings("panels/application/StorageItemsView.ts",fi),Ti=i.i18n.getLocalizedString.bind(void 0,Ci);class Ii extends l.Widget.VBox{filterRegex;refreshButton;mainToolbar;filterItem;deleteAllButton;deleteSelectedButton;metadataView=new u.StorageMetadataView.StorageMetadataView;constructor(e,t){super(!1),this.filterRegex=null,this.refreshButton=this.addButton(Ti(fi.refresh),"refresh",(()=>{this.refreshItems(),l.ARIAUtils.alert(Ti(fi.refreshedStatus))})),this.mainToolbar=new l.Toolbar.Toolbar("top-resources-toolbar",this.element),this.filterItem=new l.Toolbar.ToolbarInput(Ti(fi.filter),"",.4),this.filterItem.addEventListener(l.Toolbar.ToolbarInput.Event.TextChanged,this.filterChanged,this);const i=new l.Toolbar.ToolbarSeparator;this.deleteAllButton=this.addButton(Ti(fi.clearAll),"clear",this.deleteAllItems),this.deleteSelectedButton=this.addButton(Ti(fi.deleteSelected),"cross",this.deleteSelectedItem),this.deleteAllButton.element.id="storage-items-delete-all";const s=[this.refreshButton,this.filterItem,i,this.deleteAllButton,this.deleteSelectedButton];for(const e of s)this.mainToolbar.appendToolbarItem(e);this.contentElement.appendChild(this.metadataView)}setDeleteAllTitle(e){this.deleteAllButton.setTitle(e)}setDeleteAllGlyph(e){this.deleteAllButton.setGlyph(e)}appendToolbarItem(e){this.mainToolbar.appendToolbarItem(e)}setStorageKey(e){this.metadataView.setStorageKey(e)}addButton(e,t,i){const s=new l.Toolbar.ToolbarButton(e,t);return s.addEventListener(l.Toolbar.ToolbarButton.Events.Click,i,this),s}filterChanged({data:e}){this.filterRegex=e?new RegExp(s.StringUtilities.escapeForRegExp(e),"i"):null,this.refreshItems()}filter(e,t){if(this.filterRegex){const i=this.filterRegex;return e.filter((e=>i.test(t(e))))}return e}hasFilter(){return Boolean(this.filterRegex)}wasShown(){this.refreshItems()}setCanDeleteAll(e){this.deleteAllButton.setEnabled(e)}setCanDeleteSelected(e){this.deleteSelectedButton.setEnabled(e)}setCanRefresh(e){this.refreshButton.setEnabled(e)}setCanFilter(e){this.filterItem.setEnabled(e)}deleteAllItems(){}deleteSelectedItem(){}refreshItems(){}}var Ei=Object.freeze({__proto__:null,StorageItemsView:Ii});const Mi={sharedStorage:"Shared Storage",key:"Key",value:"Value",sharedStorageItems:"Shared Storage Items",sharedStorageItemsCleared:"Shared Storage items cleared",sharedStorageFilteredItemsCleared:"Shared Storage filtered items cleared",selectAValueToPreview:"Select a value to preview",sharedStorageItemDeleted:"The storage item was deleted.",sharedStorageItemEdited:"The storage item was edited.",sharedStorageItemEditCanceled:"The storage item edit was canceled.",sharedStorageNumberEntries:"Number of entries shown in table: {PH1}"},xi=i.i18n.registerUIStrings("panels/application/SharedStorageItemsView.ts",Mi),Ri=i.i18n.getLocalizedString.bind(void 0,xi);var Li;!function(e){let t;!function(e){e.FilteredItemsCleared="FilteredItemsCleared",e.ItemDeleted="ItemDeleted",e.ItemEdited="ItemEdited",e.ItemsCleared="ItemsCleared",e.ItemsRefreshed="ItemsRefreshed"}(t=e.Events||(e.Events={}))}(Li||(Li={}));class Di extends Ii{#y;outerSplitWidget;innerSplitWidget;#k;dataGrid;#s;#f;sharedStorageItemsDispatcher;constructor(t){super(Ri(Mi.sharedStorage),"sharedStoragePanel"),this.#y=t,this.element.classList.add("storage-view","table");const i=[{id:"key",title:Ri(Mi.key),sortable:!1,editable:!0,longText:!0,weight:50},{id:"value",title:Ri(Mi.value),sortable:!1,editable:!0,longText:!0,weight:50}];this.dataGrid=new m.DataGrid.DataGridImpl({displayName:Ri(Mi.sharedStorageItems),columns:i,editCallback:this.#C.bind(this),deleteCallback:this.#T.bind(this),refreshCallback:this.refreshItems.bind(this)}),this.dataGrid.addEventListener(m.DataGrid.Events.SelectedNode,(e=>{this.#I(e.data)})),this.dataGrid.addEventListener(m.DataGrid.Events.DeselectedNode,(()=>{this.#I(null)})),this.dataGrid.setStriped(!0),this.dataGrid.setName("SharedStorageItemsView");const s=this.dataGrid.asWidget();s.setMinimumSize(0,100),this.#k=n.LegacyWrapper.legacyWrapper(l.Widget.VBox,new u.SharedStorageMetadataView.SharedStorageMetadataView(t,t.securityOrigin)),this.#k.setMinimumSize(0,275);const r=this.#k.element.createChild("div","metadata-view-resizer");this.innerSplitWidget=new l.SplitWidget.SplitWidget(!1,!1,"sharedStorageInnerSplitViewState"),this.innerSplitWidget.setSidebarWidget(this.#k),this.innerSplitWidget.setMainWidget(s),this.innerSplitWidget.installResizer(r),this.#s=new l.Widget.VBox,this.#s.setMinimumSize(0,25);const a=this.#s.element.createChild("div","preview-panel-resizer");this.outerSplitWidget=new l.SplitWidget.SplitWidget(!1,!0,"sharedStorageOuterSplitViewState"),this.outerSplitWidget.show(this.element),this.outerSplitWidget.setMainWidget(this.innerSplitWidget),this.outerSplitWidget.setSidebarWidget(this.#s),this.outerSplitWidget.installResizer(a),this.#s.contentElement.classList.add("placeholder");this.#s.contentElement.createChild("div").textContent=Ri(Mi.selectAValueToPreview),this.#f=[],e.EventTarget.removeEventListeners(this.#f),this.#y=t,this.#f=[this.#y.addEventListener(bi.Events.SharedStorageChanged,this.#E,this)],this.sharedStorageItemsDispatcher=new e.ObjectWrapper.ObjectWrapper}static async createView(e){const t=new Di(e);return await t.updateEntriesOnly(),t}async updateEntriesOnly(){if(!this.isShowing())return;const e=await this.#y.getEntries();e&&this.#M(e)}async#E(){await this.refreshItems()}async refreshItems(){this.isShowing()&&(await this.#k.getComponent().render(),await this.updateEntriesOnly(),this.sharedStorageItemsDispatcher.dispatchEventToListeners(Li.Events.ItemsRefreshed))}async deleteSelectedItem(){this.dataGrid.selectedNode&&await this.#T(this.dataGrid.selectedNode)}async deleteAllItems(){if(!this.hasFilter())return await this.#y.clear(),await this.refreshItems(),this.sharedStorageItemsDispatcher.dispatchEventToListeners(Li.Events.ItemsCleared),void l.ARIAUtils.alert(Ri(Mi.sharedStorageItemsCleared));await Promise.all(this.dataGrid.rootNode().children.filter((e=>e.data.key)).map((e=>this.#y.deleteEntry(e.data.key)))),await this.refreshItems(),this.sharedStorageItemsDispatcher.dispatchEventToListeners(Li.Events.FilteredItemsCleared),l.ARIAUtils.alert(Ri(Mi.sharedStorageFilteredItemsCleared))}async#C(e,t,i,s){if("key"===t&&""===s)return await this.refreshItems(),void l.ARIAUtils.alert(Ri(Mi.sharedStorageItemEditCanceled));"key"===t?(await this.#y.deleteEntry(i),await this.#y.setEntry(s,e.data.value||"",!1)):await this.#y.setEntry(e.data.key||" ",s,!1),await this.refreshItems(),this.sharedStorageItemsDispatcher.dispatchEventToListeners(Li.Events.ItemEdited,{columnIdentifier:t,oldText:i,newText:s}),l.ARIAUtils.alert(Ri(Mi.sharedStorageItemEdited))}#M(e){const t=this.dataGrid.rootNode(),[i]=t.children.filter((e=>e.selected)).map((e=>e.data.key));t.removeChildren();let s=null;const r=this.filter(e,(e=>`${e.key} ${e.value}`));for(const e of r){const r=new m.DataGrid.DataGridNode({key:e.key,value:e.value},!1);r.selectable=!0,t.appendChild(r),s&&e.key!==i||(s=r)}s&&(s.selected=!0),this.dataGrid.addCreationNode(!1),this.setCanDeleteSelected(Boolean(s)),l.ARIAUtils.alert(Ri(Mi.sharedStorageNumberEntries,{PH1:r.length}))}async#T(e){if(!e||e.isCreationNode||!this.#y)return;const t=e.data.key;await this.#y.deleteEntry(t),await this.refreshItems(),this.sharedStorageItemsDispatcher.dispatchEventToListeners(Li.Events.ItemDeleted,{key:t}),l.ARIAUtils.alert(Ri(Mi.sharedStorageItemDeleted))}async#I(e){const t=e?.data?.key,i=e?.data?.value,s=t&&{key:t,value:i||""};if(s){const t=d.JSONView.JSONView.createViewSync(s);e.selected&&this.outerSplitWidget.setSidebarWidget(t)}else this.outerSplitWidget.setSidebarWidget(this.#s)}getEntriesForTesting(){return this.dataGrid.rootNode().children.filter((e=>e.data.key)).map((e=>e.data))}}var Pi=Object.freeze({__proto__:null,get SharedStorageItemsDispatcher(){return Li},SharedStorageItemsView:Di});class Bi extends D{view;constructor(e,t){super(e,t.securityOrigin,!1)}static async createElement(e,t){const i=new Bi(e,t);return i.view=await Di.createView(t),i}get itemURL(){return"shared-storage://"}onselect(e){return super.onselect(e),this.resourcesPanel.showView(this.view),!1}}var Fi=Object.freeze({__proto__:null,SharedStorageTreeElement:Bi});const Vi=new CSSStyleSheet;Vi.replaceSync(".report-row{display:flex;align-items:center;white-space:normal}.clear-storage-button .report-row{margin:0 0 0 17px;display:flex}.link{margin-left:10px;display:none}.report-row:hover .link{display:inline}.quota-override-editor-with-button{align-items:baseline;display:flex}.quota-override-notification-editor{border:solid 1px var(--color-details-hairline);display:flex;flex:auto;margin-right:4px;max-width:200px;min-width:50px;min-height:24px;padding-left:4px}.quota-override-notification-editor:focus{border:solid 1px var(--color-primary-variant)}.quota-override-error{padding-top:10px;color:#f00}.usage-breakdown-row{min-width:fit-content}.clear-storage-container{overflow:auto}.clear-storage-header{min-width:400px}.report-content-box{overflow:initial}.include-third-party-cookies{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-left:16px}\n/*# sourceURL=storageView.css */\n");const Ai={storageQuotaUsed:"{PH1} used out of {PH2} storage quota",storageQuotaUsedWithBytes:"{PH1} bytes used out of {PH2} bytes storage quota",storageWithCustomMarker:"{PH1} (custom)",storageTitle:"Storage",usage:"Usage",mb:"MB",learnMore:"Learn more",clearSiteData:"Clear site data",SiteDataCleared:"Site data cleared",application:"Application",unregisterServiceWorker:"Unregister service workers",localAndSessionStorage:"Local and session storage",indexDB:"IndexedDB",webSql:"Web SQL",cookies:"Cookies",cache:"Cache",cacheStorage:"Cache storage",includingThirdPartyCookies:"including third-party cookies",sFailedToLoad:"{PH1} (failed to load)",internalError:"Internal error",pleaseEnterANumber:"Please enter a number",numberMustBeNonNegative:"Number must be non-negative",numberMustBeSmaller:"Number must be smaller than {PH1}",clearing:"Clearing...",storageQuotaIsLimitedIn:"Storage quota is limited in Incognito mode",fileSystem:"File System",other:"Other",storageUsage:"Storage usage",serviceWorkers:"Service Workers",simulateCustomStorage:"Simulate custom storage quota"},Oi=i.i18n.registerUIStrings("panels/application/StorageView.ts",Ai),Wi=i.i18n.getLocalizedString.bind(void 0,Oi);class Ui extends l.ThrottledWidget.ThrottledWidget{pieColors;reportView;target;securityOrigin;storageKey;settings;includeThirdPartyCookiesSetting;quotaRow;quotaUsage;pieChart;previousOverrideFieldValue;quotaOverrideCheckbox;quotaOverrideControlRow;quotaOverrideEditor;quotaOverrideErrorMessage;clearButton;constructor(){super(!0,1e3),this.contentElement.classList.add("clear-storage-container"),this.pieColors=new Map([["appcache","rgb(110, 161, 226)"],["cache_storage","rgb(229, 113, 113)"],["cookies","rgb(239, 196, 87)"],["indexeddb","rgb(155, 127, 230)"],["local_storage","rgb(116, 178, 102)"],["service_workers","rgb(255, 167, 36)"],["websql","rgb(203, 220, 56)"]]),this.reportView=new l.ReportView.ReportView(Wi(Ai.storageTitle)),this.reportView.element.classList.add("clear-storage-header"),this.reportView.show(this.contentElement),this.target=null,this.securityOrigin=null,this.storageKey=null,this.settings=new Map;for(const t of Ni)this.settings.set(t,e.Settings.Settings.instance().createSetting("clear-storage-"+t,!0));this.includeThirdPartyCookiesSetting=e.Settings.Settings.instance().createSetting("clear-storage-include-third-party-cookies",!1);const t=this.reportView.appendSection(Wi(Ai.usage));this.quotaRow=t.appendSelectableRow(),this.quotaRow.classList.add("quota-usage-row");const i=t.appendRow(),s=l.XLink.XLink.create("https://developer.chrome.com/docs/devtools/progressive-web-apps#opaque-responses",Wi(Ai.learnMore));i.appendChild(s),this.quotaUsage=null,this.pieChart=new M.PieChart.PieChart,this.populatePieChart(0,[]);const r=t.appendRow();r.classList.add("usage-breakdown-row"),r.appendChild(this.pieChart),this.previousOverrideFieldValue="";const a=t.appendRow();a.classList.add("quota-override-row"),this.quotaOverrideCheckbox=l.UIUtils.CheckboxLabel.create(Wi(Ai.simulateCustomStorage),!1,""),a.appendChild(this.quotaOverrideCheckbox),this.quotaOverrideCheckbox.checkboxElement.addEventListener("click",this.onClickCheckbox.bind(this),!1),this.quotaOverrideControlRow=t.appendRow(),this.quotaOverrideEditor=this.quotaOverrideControlRow.createChild("input","quota-override-notification-editor"),this.quotaOverrideControlRow.appendChild(l.UIUtils.createLabel(Wi(Ai.mb))),this.quotaOverrideControlRow.classList.add("hidden"),this.quotaOverrideEditor.addEventListener("keyup",(e=>{"Enter"===e.key&&(this.applyQuotaOverrideFromInputField(),e.consume(!0))})),this.quotaOverrideEditor.addEventListener("focusout",(e=>{this.applyQuotaOverrideFromInputField(),e.consume(!0)}));const n=t.appendRow();this.quotaOverrideErrorMessage=n.createChild("div","quota-override-error");const d=this.reportView.appendSection("","clear-storage-button").appendRow();this.clearButton=l.UIUtils.createTextButton(Wi(Ai.clearSiteData),this.clear.bind(this)),this.clearButton.id="storage-view-clear-button",d.appendChild(this.clearButton);const c=l.SettingsUI.createSettingCheckbox(Wi(Ai.includingThirdPartyCookies),this.includeThirdPartyCookiesSetting,!0);c.classList.add("include-third-party-cookies"),d.appendChild(c);const h=this.reportView.appendSection(Wi(Ai.application));this.appendItem(h,Wi(Ai.unregisterServiceWorker),"service_workers"),h.markFieldListAsGroup();const g=this.reportView.appendSection(Wi(Ai.storageTitle));this.appendItem(g,Wi(Ai.localAndSessionStorage),"local_storage"),this.appendItem(g,Wi(Ai.indexDB),"indexeddb"),this.appendItem(g,Wi(Ai.webSql),"websql"),this.appendItem(g,Wi(Ai.cookies),"cookies"),g.markFieldListAsGroup();const u=this.reportView.appendSection(Wi(Ai.cache));this.appendItem(u,Wi(Ai.cacheStorage),"cache_storage"),u.markFieldListAsGroup(),o.TargetManager.TargetManager.instance().observeTargets(this)}appendItem(e,t,i){const s=e.appendRow(),r=this.settings.get(i);r&&s.appendChild(l.SettingsUI.createSettingCheckbox(t,r,!0))}targetAdded(e){if(e!==o.TargetManager.TargetManager.instance().primaryPageTarget())return;this.target=e;const t=e.model(o.SecurityOriginManager.SecurityOriginManager);this.updateOrigin(t.mainSecurityOrigin(),t.unreachableMainSecurityOrigin()),t.addEventListener(o.SecurityOriginManager.Events.MainSecurityOriginChanged,this.originChanged,this);const i=e.model(o.StorageKeyManager.StorageKeyManager);this.updateStorageKey(i.mainStorageKey()),i.addEventListener(o.StorageKeyManager.Events.MainStorageKeyChanged,this.storageKeyChanged,this)}targetRemoved(e){if(this.target!==e)return;e.model(o.SecurityOriginManager.SecurityOriginManager).removeEventListener(o.SecurityOriginManager.Events.MainSecurityOriginChanged,this.originChanged,this);e.model(o.StorageKeyManager.StorageKeyManager).removeEventListener(o.StorageKeyManager.Events.MainStorageKeyChanged,this.storageKeyChanged,this)}originChanged(e){const{mainSecurityOrigin:t,unreachableMainSecurityOrigin:i}=e.data;this.updateOrigin(t,i)}storageKeyChanged(e){const{mainStorageKey:t}=e.data;this.updateStorageKey(t)}updateOrigin(e,t){const i=this.securityOrigin;t?(this.securityOrigin=t,this.reportView.setSubtitle(Wi(Ai.sFailedToLoad,{PH1:t}))):(this.securityOrigin=e,this.reportView.setSubtitle(e)),i!==this.securityOrigin&&(this.quotaOverrideControlRow.classList.add("hidden"),this.quotaOverrideCheckbox.checkboxElement.checked=!1,this.quotaOverrideErrorMessage.textContent=""),this.doUpdate()}updateStorageKey(e){const t=this.storageKey;this.storageKey=e,this.reportView.setSubtitle(e),t!==this.storageKey&&(this.quotaOverrideControlRow.classList.add("hidden"),this.quotaOverrideCheckbox.checkboxElement.checked=!1,this.quotaOverrideErrorMessage.textContent=""),this.doUpdate()}async applyQuotaOverrideFromInputField(){if(!this.target||!this.securityOrigin)return void(this.quotaOverrideErrorMessage.textContent=Wi(Ai.internalError));this.quotaOverrideErrorMessage.textContent="";const e=this.quotaOverrideEditor.value;if(""===e)return await this.clearQuotaForOrigin(this.target,this.securityOrigin),void(this.previousOverrideFieldValue="");const t=parseFloat(e);if(!Number.isFinite(t))return void(this.quotaOverrideErrorMessage.textContent=Wi(Ai.pleaseEnterANumber));if(t<0)return void(this.quotaOverrideErrorMessage.textContent=Wi(Ai.numberMustBeNonNegative));const i=9e12;if(t>=i)return void(this.quotaOverrideErrorMessage.textContent=Wi(Ai.numberMustBeSmaller,{PH1:i.toLocaleString()}));const s=1e6,r=Math.round(t*s),a=""+r/s;this.quotaOverrideEditor.value=a,this.previousOverrideFieldValue=a,await this.target.storageAgent().invoke_overrideQuotaForOrigin({origin:this.securityOrigin,quotaSize:r})}async clearQuotaForOrigin(e,t){await e.storageAgent().invoke_overrideQuotaForOrigin({origin:t})}async onClickCheckbox(){this.quotaOverrideControlRow.classList.contains("hidden")?(this.quotaOverrideControlRow.classList.remove("hidden"),this.quotaOverrideCheckbox.checkboxElement.checked=!0,this.quotaOverrideEditor.value=this.previousOverrideFieldValue,this.quotaOverrideEditor.focus()):this.target&&this.securityOrigin&&(this.quotaOverrideControlRow.classList.add("hidden"),this.quotaOverrideCheckbox.checkboxElement.checked=!1,await this.clearQuotaForOrigin(this.target,this.securityOrigin),this.quotaOverrideErrorMessage.textContent="")}clear(){if(!this.securityOrigin)return;const e=[];for(const t of this.settings.keys()){const i=this.settings.get(t);i&&i.get()&&e.push(t)}if(this.target){const t=this.includeThirdPartyCookiesSetting.get();Ui.clear(this.target,this.storageKey,this.securityOrigin,e,t)}this.clearButton.disabled=!0;const t=this.clearButton.textContent;this.clearButton.textContent=Wi(Ai.clearing),window.setTimeout((()=>{this.clearButton.disabled=!1,this.clearButton.textContent=t,this.clearButton.focus()}),500),l.ARIAUtils.alert(Wi(Ai.SiteDataCleared))}static clear(e,t,i,s,r){if(console.assert(Boolean(t)),!t)return;e.storageAgent().invoke_clearDataForStorageKey({storageKey:t,storageTypes:s.join(",")});const a=new Set(s),n=a.has("all");if(a.has("local_storage")||n){const i=e.model(ot);i&&i.clearForStorageKey(t)}if(a.has("indexeddb")||n)for(const e of o.TargetManager.TargetManager.instance().targets()){const i=e.model(lt);i&&i.clearForStorageKey(t)}if(i&&(a.has("cookies")||n)){e.storageAgent().invoke_clearDataForOrigin({origin:i,storageTypes:"cookies"});const t=e.model(o.CookieModel.CookieModel);t&&t.clear(void 0,r?void 0:i)}if(a.has("websql")||n){const t=e.model(_e);t&&(t.disable(),t.enable())}if(a.has("cache_storage")||n){const e=o.TargetManager.TargetManager.instance().primaryPageTarget(),i=e&&e.model(o.ServiceWorkerCacheModel.ServiceWorkerCacheModel);i&&i.clearForStorageKey(t)}}async doUpdate(){if(!this.securityOrigin||!this.target)return this.quotaRow.textContent="",void this.populatePieChart(0,[]);const e=this.securityOrigin,t=await this.target.storageAgent().invoke_getUsageAndQuota({origin:e});if(this.quotaRow.textContent="",t.getError())return void this.populatePieChart(0,[]);const r=t.overrideActive,a=s.NumberUtilities.bytesToString(t.quota),o=s.NumberUtilities.bytesToString(t.usage),n=Wi(Ai.storageWithCustomMarker,{PH1:a}),d=r?l.Fragment.Fragment.build`<b>${n}</b>`.element():a,c=i.i18n.getFormatLocalizedString(Oi,Ai.storageQuotaUsed,{PH1:o,PH2:d});if(this.quotaRow.appendChild(c),l.Tooltip.Tooltip.install(this.quotaRow,Wi(Ai.storageQuotaUsedWithBytes,{PH1:t.usage.toLocaleString(),PH2:t.quota.toLocaleString()})),!t.overrideActive&&t.quota<125829120){const e=new g.Icon.Icon;e.data={iconName:"info",color:"var(--icon-info)",width:"14px",height:"14px"},l.Tooltip.Tooltip.install(this.quotaRow,Wi(Ai.storageQuotaIsLimitedIn)),this.quotaRow.appendChild(e)}if(null===this.quotaUsage||this.quotaUsage!==t.usage){this.quotaUsage=t.usage;const e=[];for(const i of t.usageBreakdown.sort(((e,t)=>t.usage-e.usage))){const t=i.usage;if(!t)continue;const s=this.getStorageTypeName(i.storageType),r=this.pieColors.get(i.storageType)||"#ccc";e.push({value:t,color:r,title:s})}this.populatePieChart(t.usage,e)}this.update()}populatePieChart(e,t){this.pieChart.data={chartName:Wi(Ai.storageUsage),size:110,formatter:s.NumberUtilities.bytesToString,showLegend:!0,total:e,slices:t}}getStorageTypeName(e){switch(e){case"file_systems":return Wi(Ai.fileSystem);case"websql":return Wi(Ai.webSql);case"appcache":return Wi(Ai.application);case"indexeddb":return Wi(Ai.indexDB);case"cache_storage":return Wi(Ai.cacheStorage);case"service_workers":return Wi(Ai.serviceWorkers);default:return Wi(Ai.other)}}wasShown(){super.wasShown(),this.reportView.registerCSSFiles([Vi]),this.registerCSSFiles([Vi])}}const Ni=["appcache","cache_storage","cookies","indexeddb","local_storage","service_workers","websql"];let Hi;class _i{static instance(e={forceNew:null}){const{forceNew:t}=e;return Hi&&!t||(Hi=new _i),Hi}handleAction(e,t){switch(t){case"resources.clear":return this.handleClear(!1);case"resources.clear-incl-third-party-cookies":return this.handleClear(!0)}return!1}handleClear(e){const t=o.TargetManager.TargetManager.instance().primaryPageTarget();if(!t)return!1;const i=t.model(o.ResourceTreeModel.ResourceTreeModel);if(!i)return!1;const s=i.getMainSecurityOrigin();return i.getMainStorageKey().then((i=>{Ui.clear(t,i,s,Ni,e)}),(e=>{})),!0}}var Gi=Object.freeze({__proto__:null,StorageView:Ui,AllStorageTypes:Ni,ActionDelegate:_i});const qi={trustTokens:"Private State Tokens"},Ki=i.i18n.registerUIStrings("panels/application/TrustTokensTreeElement.ts",qi),ji=i.i18n.getLocalizedString.bind(void 0,Ki);class zi extends D{view;constructor(e){super(e,ji(qi.trustTokens),!1);const t=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([t])}get itemURL(){return"trustTokens://"}onselect(e){return super.onselect(e),this.view||(this.view=new Qi(new u.TrustTokensView.TrustTokensView)),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.trust_tokens]),!1}}class Qi extends l.ThrottledWidget.ThrottledWidget{trustTokensView;constructor(e){super(!1,1e3),this.trustTokensView=e,this.contentElement.appendChild(this.trustTokensView),this.update()}async doUpdate(){const e=o.TargetManager.TargetManager.instance().primaryPageTarget();if(!e)return;const{tokens:t}=await e.storageAgent().invoke_getTrustTokens();this.trustTokensView.data={tokens:t,deleteClickHandler:t=>{e.storageAgent().invoke_clearTrustTokens({issuerOrigin:t})}},this.update()}}var $i=Object.freeze({__proto__:null,i18nString:ji,TrustTokensTreeElement:zi,TrustTokensViewWidgetWrapper:Qi});const Ji=new CSSStyleSheet;Ji.replaceSync(".placeholder{display:flex;align-items:center;justify-content:center;font-size:13px;color:var(--color-text-secondary)}\n/*# sourceURL=reportingApiReportsView.css */\n");const Xi={clickToDisplayBody:"Click on any report to display its body"},Yi=i.i18n.registerUIStrings("panels/application/ReportingApiReportsView.ts",Xi),Zi=i.i18n.getLocalizedString.bind(void 0,Yi);class es extends l.SplitWidget.SplitWidget{reportsGrid=new u.ReportsGrid.ReportsGrid;reports=[];constructor(e){super(!1,!0);const t=new l.Widget.VBox,i=new l.Widget.VBox;t.setMinimumSize(0,80),this.setMainWidget(t),i.setMinimumSize(0,40),this.setSidebarWidget(i),t.contentElement.appendChild(this.reportsGrid),this.reportsGrid.addEventListener("cellfocused",this.onFocus.bind(this)),i.contentElement.classList.add("placeholder");i.contentElement.createChild("div").textContent=Zi(Xi.clickToDisplayBody),e.addEventListener(o.NetworkManager.Events.ReportingApiReportAdded,(e=>this.onReportAdded(e.data)),this),e.addEventListener(o.NetworkManager.Events.ReportingApiReportUpdated,(e=>this.onReportUpdated(e.data)),this)}wasShown(){super.wasShown();const e=this.sidebarWidget();e&&e.registerCSSFiles([Ji])}onReportAdded(e){this.reports.push(e),this.reportsGrid.data={reports:this.reports}}onReportUpdated(e){const t=this.reports.findIndex((t=>t.id===e.id));this.reports[t]=e,this.reportsGrid.data={reports:this.reports}}async onFocus(e){const t=e.data.row.cells.find((e=>"id"===e.columnId)),i=t&&this.reports.find((e=>e.id===t.value));if(i){const e=await d.JSONView.JSONView.createView(JSON.stringify(i.body));e?.setMinimumSize(0,40),e&&this.setSidebarWidget(e)}}getReports(){return this.reports}getReportsGrid(){return this.reportsGrid}}var ts=Object.freeze({__proto__:null,i18nString:Zi,ReportingApiReportsView:es});class is extends l.SplitWidget.SplitWidget{endpointsGrid;endpoints;constructor(e){super(!1,!0),this.endpointsGrid=e,this.endpoints=new Map;const t=o.TargetManager.TargetManager.instance().primaryPageTarget(),i=t&&t.model(o.NetworkManager.NetworkManager);if(i){i.addEventListener(o.NetworkManager.Events.ReportingApiEndpointsChangedForOrigin,(e=>this.onEndpointsChangedForOrigin(e.data)),this);const e=new es(i),t=new l.Widget.VBox;t.setMinimumSize(0,40),t.contentElement.appendChild(this.endpointsGrid),this.setMainWidget(e),this.setSidebarWidget(t),i.enableReportingApi()}}onEndpointsChangedForOrigin(e){this.endpoints.set(e.origin,e.endpoints),this.endpointsGrid.data={endpoints:this.endpoints}}}var ss=Object.freeze({__proto__:null,ReportingApiView:is});const rs={reportingApi:"Reporting API"},as=i.i18n.registerUIStrings("panels/application/ReportingApiTreeElement.ts",rs),os=i.i18n.getLocalizedString.bind(void 0,as);class ns extends D{view;constructor(e){super(e,os(rs.reportingApi),!1);const t=l.Icon.Icon.create("document","resource-tree-item");this.setLeadingIcons([t])}get itemURL(){return"reportingApi://"}onselect(e){return super.onselect(e),this.view||(this.view=new is(new u.EndpointsGrid.EndpointsGrid)),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.reporting_api]),!1}}const ds={application:"Application",storage:"Storage",localStorage:"Local Storage",sessionStorage:"Session Storage",webSql:"Web SQL",cookies:"Cookies",backgroundServices:"Background Services",preloading:"Preloading",frames:"Frames",manifest:"Manifest",noManifestDetected:"No manifest detected",appManifest:"App Manifest",indexeddb:"IndexedDB",refreshIndexeddb:"Refresh IndexedDB",versionSEmpty:"Version: {PH1} (empty)",versionS:"Version: {PH1}",clear:"Clear",keyPathS:"Key path: {PH1}",localFiles:"Local Files",cookiesUsedByFramesFromS:"Cookies used by frames from {PH1}",openedWindows:"Opened Windows",webWorkers:"Web Workers",documentNotAvailable:"Document not available",theContentOfThisDocumentHasBeen:"The content of this document has been generated dynamically via 'document.write()'.",windowWithoutTitle:"Window without title",worker:"worker",onInvokeManifestAlert:"Manifest: Invoke to scroll to the top of manifest",beforeInvokeAlert:"{PH1}: Invoke to scroll to this section in manifest",onInvokeAlert:"Scrolled to {PH1}",applicationSidebarPanel:"Application panel sidebar"},ls=i.i18n.registerUIStrings("panels/application/ApplicationPanelSidebar.ts",ds),cs=i.i18n.getLocalizedString.bind(void 0,ls);function hs(e){if("main"===e)throw new Error("Unexpected main target id")}var gs;!function(e){let t;!function(e){e.SharedStorageTreeElementAdded="SharedStorageTreeElementAdded"}(t=e.Events||(e.Events={}))}(gs||(gs={}));class us extends l.Widget.VBox{panel;sidebarTree;applicationTreeElement;serviceWorkersTreeElement;localStorageListTreeElement;sessionStorageListTreeElement;indexedDBListTreeElement;interestGroupTreeElement;databasesListTreeElement;cookieListTreeElement;trustTokensTreeElement;cacheStorageListTreeElement;sharedStorageListTreeElement;backForwardCacheListTreeElement;backgroundFetchTreeElement;backgroundSyncTreeElement;bounceTrackingMitigationsTreeElement;notificationsTreeElement;paymentHandlerTreeElement;periodicBackgroundSyncTreeElement;pushMessagingTreeElement;reportingApiTreeElement;preloadingTreeElement;preloadingResultTreeElement;resourcesSection;databaseTableViews;databaseQueryViews;databaseTreeElements;domStorageTreeElements;sharedStorageTreeElements;domains;target;databaseModel;previousHoveredElement;sharedStorageTreeElementDispatcher;constructor(t){super(),this.panel=t,this.sidebarTree=new l.TreeOutline.TreeOutlineInShadow,this.sidebarTree.element.classList.add("resources-sidebar"),this.sidebarTree.element.classList.add("filter-all"),this.sidebarTree.addEventListener(l.TreeOutline.Events.ElementAttached,this.treeElementAdded,this),this.contentElement.appendChild(this.sidebarTree.element);const i=cs(ds.application);this.applicationTreeElement=this.addSidebarSection(i);const s=this.applicationTreeElement.treeOutline?.contentElement;s&&(s.ariaLabel=cs(ds.applicationSidebarPanel));const r=new Ss(t);this.applicationTreeElement.appendChild(r),r.generateChildren(),this.serviceWorkersTreeElement=new vs(t),this.applicationTreeElement.appendChild(this.serviceWorkersTreeElement);const n=new ys(t);this.applicationTreeElement.appendChild(n);const d=cs(ds.storage),c=this.addSidebarSection(d);this.localStorageListTreeElement=new P(t,cs(ds.localStorage),"LocalStorage"),this.localStorageListTreeElement.setLink("https://developer.chrome.com/docs/devtools/storage/localstorage/?utm_source=devtools");const h=l.Icon.Icon.create("table","resource-tree-item");this.localStorageListTreeElement.setLeadingIcons([h]),c.appendChild(this.localStorageListTreeElement),this.sessionStorageListTreeElement=new P(t,cs(ds.sessionStorage),"SessionStorage"),this.sessionStorageListTreeElement.setLink("https://developer.chrome.com/docs/devtools/storage/sessionstorage/?utm_source=devtools");const g=l.Icon.Icon.create("table","resource-tree-item");this.sessionStorageListTreeElement.setLeadingIcons([g]),c.appendChild(this.sessionStorageListTreeElement),this.indexedDBListTreeElement=new ks(t),this.indexedDBListTreeElement.setLink("https://developer.chrome.com/docs/devtools/storage/indexeddb/?utm_source=devtools"),c.appendChild(this.indexedDBListTreeElement),this.databasesListTreeElement=new P(t,cs(ds.webSql),"Databases"),this.databasesListTreeElement.setLink("https://developer.chrome.com/docs/devtools/storage/websql/?utm_source=devtools");const u=l.Icon.Icon.create("database","resource-tree-item");this.databasesListTreeElement.setLeadingIcons([u]),c.appendChild(this.databasesListTreeElement),this.cookieListTreeElement=new P(t,cs(ds.cookies),"Cookies"),this.cookieListTreeElement.setLink("https://developer.chrome.com/docs/devtools/storage/cookies/?utm_source=devtools");const p=l.Icon.Icon.create("cookie","resource-tree-item");this.cookieListTreeElement.setLeadingIcons([p]),c.appendChild(this.cookieListTreeElement),this.trustTokensTreeElement=new zi(t),c.appendChild(this.trustTokensTreeElement),this.interestGroupTreeElement=new Ot(t),c.appendChild(this.interestGroupTreeElement),this.sharedStorageListTreeElement=new wi(t),c.appendChild(this.sharedStorageListTreeElement),this.cacheStorageListTreeElement=new Ae(t),c.appendChild(this.cacheStorageListTreeElement);const m=cs(ds.backgroundServices),w=this.addSidebarSection(m);if(this.backForwardCacheListTreeElement=new _(t),w.appendChild(this.backForwardCacheListTreeElement),this.backgroundFetchTreeElement=new ps(t,"backgroundFetch"),w.appendChild(this.backgroundFetchTreeElement),this.backgroundSyncTreeElement=new ps(t,"backgroundSync"),w.appendChild(this.backgroundSyncTreeElement),this.bounceTrackingMitigationsTreeElement=new ae(t),w.appendChild(this.bounceTrackingMitigationsTreeElement),this.notificationsTreeElement=new ps(t,"notifications"),w.appendChild(this.notificationsTreeElement),this.paymentHandlerTreeElement=new ps(t,"paymentHandler"),w.appendChild(this.paymentHandlerTreeElement),this.periodicBackgroundSyncTreeElement=new ps(t,"periodicBackgroundSync"),w.appendChild(this.periodicBackgroundSyncTreeElement),this.pushMessagingTreeElement=new ps(t,"pushMessaging"),w.appendChild(this.pushMessagingTreeElement),this.reportingApiTreeElement=new ns(t),w.appendChild(this.reportingApiTreeElement),a.Runtime.experiments.isEnabled(a.Runtime.ExperimentName.PRELOADING_STATUS_PANEL)){const e=cs(ds.preloading),i=this.addSidebarSection(e);this.preloadingTreeElement=ke.newForPreloadingView(t),this.preloadingResultTreeElement=ke.newForPreloadingResultView(t),i.appendChild(this.preloadingTreeElement),i.appendChild(this.preloadingResultTreeElement)}const v=cs(ds.frames),S=this.addSidebarSection(v);this.resourcesSection=new xs(t,S),this.databaseTableViews=new Map,this.databaseQueryViews=new Map,this.databaseTreeElements=new Map,this.domStorageTreeElements=new Map,this.sharedStorageTreeElements=new Map,this.domains={},this.sidebarTree.contentElement.addEventListener("mousemove",this.onmousemove.bind(this),!1),this.sidebarTree.contentElement.addEventListener("mouseleave",this.onmouseleave.bind(this),!1),o.TargetManager.TargetManager.instance().observeTargets(this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.ResourceTreeModel.ResourceTreeModel,o.ResourceTreeModel.Events.FrameNavigated,this.frameNavigated,this,{scoped:!0});this.panel.lastSelectedItemPath().length||r.select(),o.TargetManager.TargetManager.instance().observeModels(ot,{modelAdded:e=>this.domStorageModelAdded(e),modelRemoved:e=>this.domStorageModelRemoved(e)},{scoped:!0}),o.TargetManager.TargetManager.instance().observeModels(lt,{modelAdded:e=>e.enable(),modelRemoved:e=>this.indexedDBListTreeElement.removeIndexedDBForModel(e)},{scoped:!0}),o.TargetManager.TargetManager.instance().observeModels(Et,{modelAdded:e=>this.interestGroupModelAdded(e),modelRemoved:e=>this.interestGroupModelRemoved(e)},{scoped:!0}),o.TargetManager.TargetManager.instance().observeModels(yi,{modelAdded:e=>this.sharedStorageModelAdded(e).catch((e=>{console.error(e)})),modelRemoved:e=>this.sharedStorageModelRemoved(e)},{scoped:!0}),o.TargetManager.TargetManager.instance().observeModels(o.StorageBucketsModel.StorageBucketsModel,{modelAdded:e=>e.enable(),modelRemoved:()=>{}},{scoped:!0}),this.sharedStorageTreeElementDispatcher=new e.ObjectWrapper.ObjectWrapper,this.contentElement.style.contain="layout style"}addSidebarSection(e){const t=new l.TreeOutline.TreeElement(e,!0);return t.listItemElement.classList.add("storage-group-list-item"),t.setCollapsible(!1),t.selectable=!1,this.sidebarTree.appendChild(t),l.ARIAUtils.markAsHeading(t.listItemElement,3),l.ARIAUtils.setLabel(t.childrenListElement,e),t}targetAdded(e){if(e!==e.outermostTarget())return;this.target=e,this.databaseModel=e.model(_e),this.databaseModel&&(this.databaseModel.addEventListener(Ge.DatabaseAdded,this.databaseAdded,this),this.databaseModel.addEventListener(Ge.DatabasesRemoved,this.resetWebSQL,this));const t=e.model(Et);t&&t.addEventListener(Tt.InterestGroupAccess,this.interestGroupAccess,this);const i=e.model(o.ResourceTreeModel.ResourceTreeModel);i&&(i.cachedResourcesLoaded()&&this.initialize(),i.addEventListener(o.ResourceTreeModel.Events.CachedResourcesLoaded,this.initialize,this),i.addEventListener(o.ResourceTreeModel.Events.WillLoadCachedResources,this.resetWithFrames,this))}targetRemoved(e){if(e!==this.target)return;delete this.target;const t=e.model(o.ResourceTreeModel.ResourceTreeModel);t&&(t.removeEventListener(o.ResourceTreeModel.Events.CachedResourcesLoaded,this.initialize,this),t.removeEventListener(o.ResourceTreeModel.Events.WillLoadCachedResources,this.resetWithFrames,this)),this.databaseModel&&(this.databaseModel.removeEventListener(Ge.DatabaseAdded,this.databaseAdded,this),this.databaseModel.removeEventListener(Ge.DatabasesRemoved,this.resetWebSQL,this),this.databaseModel=null);const i=e.model(Et);i&&i.removeEventListener(Tt.InterestGroupAccess,this.interestGroupAccess,this),this.resetWithFrames()}focus(){this.sidebarTree.focus()}initialize(){for(const e of o.ResourceTreeModel.ResourceTreeModel.frames())this.addCookieDocument(e);this.databaseModel&&this.databaseModel.enable();const e=this.target&&this.target.model(Et);e&&e.enable(),this.cacheStorageListTreeElement.initialize();const t=this.target&&this.target.model(G)||null;if(this.backgroundFetchTreeElement&&this.backgroundFetchTreeElement.initialize(t),this.backgroundSyncTreeElement&&this.backgroundSyncTreeElement.initialize(t),this.notificationsTreeElement.initialize(t),this.paymentHandlerTreeElement.initialize(t),this.periodicBackgroundSyncTreeElement.initialize(t),this.pushMessagingTreeElement.initialize(t),a.Runtime.experiments.isEnabled(a.Runtime.ExperimentName.PRELOADING_STATUS_PANEL)){const e=this.target?.model(o.PreloadingModel.PreloadingModel);e&&(this.preloadingTreeElement?.initialize(e),this.preloadingResultTreeElement?.initialize(e))}}domStorageModelAdded(e){e.enable(),e.storages().forEach(this.addDOMStorage.bind(this)),e.addEventListener(st.DOMStorageAdded,this.domStorageAdded,this),e.addEventListener(st.DOMStorageRemoved,this.domStorageRemoved,this)}domStorageModelRemoved(e){e.storages().forEach(this.removeDOMStorage.bind(this)),e.removeEventListener(st.DOMStorageAdded,this.domStorageAdded,this),e.removeEventListener(st.DOMStorageRemoved,this.domStorageRemoved,this)}interestGroupModelAdded(e){e.enable(),e.addEventListener(Tt.InterestGroupAccess,this.interestGroupAccess,this)}interestGroupModelRemoved(e){e.disable(),e.removeEventListener(Tt.InterestGroupAccess,this.interestGroupAccess,this)}async sharedStorageModelAdded(e){await e.enable();for(const t of e.storages())await this.addSharedStorage(t);e.addEventListener(vi.SharedStorageAdded,this.sharedStorageAdded,this),e.addEventListener(vi.SharedStorageRemoved,this.sharedStorageRemoved,this),e.addEventListener(vi.SharedStorageAccess,this.sharedStorageAccess,this)}sharedStorageModelRemoved(e){e.disable();for(const t of e.storages())this.removeSharedStorage(t);e.removeEventListener(vi.SharedStorageAdded,this.sharedStorageAdded,this),e.removeEventListener(vi.SharedStorageRemoved,this.sharedStorageRemoved,this),e.removeEventListener(vi.SharedStorageAccess,this.sharedStorageAccess,this)}resetWithFrames(){this.resourcesSection.reset(),this.reset()}resetWebSQL(){for(const e of this.databaseQueryViews.values())e.removeEventListener(Je.SchemaUpdated,(e=>{this.updateDatabaseTables(e)}),this);this.databaseTableViews.clear(),this.databaseQueryViews.clear(),this.databaseTreeElements.clear(),this.databasesListTreeElement.removeChildren(),this.databasesListTreeElement.setExpandable(!1)}treeElementAdded(e){const t=this.panel.lastSelectedItemPath();if(!t.length)return;const i=e.data,s=[i];for(let e=i.parent;e&&"itemURL"in e&&e.itemURL;e=e.parent)s.push(e);let r=t.length-1,a=s.length-1;for(;r>=0&&a>=0&&t[r]===s[a].itemURL;)s[a].expanded||(r>0&&s[a].expand(),s[a].selected||s[a].select()),r--,a--}reset(){this.domains={},this.resetWebSQL(),this.cookieListTreeElement.removeChildren(),this.interestGroupTreeElement.clearEvents()}frameNavigated(e){const t=e.data;t.isOutermostFrame()&&this.reset(),this.addCookieDocument(t)}databaseAdded({data:e}){const t=new ms(this,e);this.databaseTreeElements.set(e,t),this.databasesListTreeElement.appendChild(t)}interestGroupAccess(e){this.interestGroupTreeElement.addEvent(e.data)}addCookieDocument(t){const i=t.unreachableUrl()||t.url,s=e.ParsedURL.ParsedURL.fromString(i);if(!s||"http"!==s.scheme&&"https"!==s.scheme&&"file"!==s.scheme)return;const r=s.securityOrigin();if(!this.domains[r]){this.domains[r]=!0;const e=new Es(this.panel,t,r);this.cookieListTreeElement.appendChild(e)}}domStorageAdded(e){const t=e.data;this.addDOMStorage(t)}addDOMStorage(e){console.assert(!this.domStorageTreeElements.get(e)),console.assert(Boolean(e.storageKey));const t=new Is(this.panel,e);this.domStorageTreeElements.set(e,t),e.isLocalStorage?this.localStorageListTreeElement.appendChild(t):this.sessionStorageListTreeElement.appendChild(t)}domStorageRemoved(e){const t=e.data;this.removeDOMStorage(t)}removeDOMStorage(e){const t=this.domStorageTreeElements.get(e);if(!t)return;const i=t.selected,s=t.parent;s&&(s.removeChild(t),i&&s.select()),this.domStorageTreeElements.delete(e)}async sharedStorageAdded(e){await this.addSharedStorage(e.data)}async addSharedStorage(e){const t=await Bi.createElement(this.panel,e);this.sharedStorageTreeElements.has(e.securityOrigin)||(this.sharedStorageTreeElements.set(e.securityOrigin,t),this.sharedStorageListTreeElement.appendChild(t),this.sharedStorageTreeElementDispatcher.dispatchEventToListeners(gs.Events.SharedStorageTreeElementAdded,{origin:e.securityOrigin}))}sharedStorageRemoved(e){this.removeSharedStorage(e.data)}removeSharedStorage(e){const t=this.sharedStorageTreeElements.get(e.securityOrigin);if(!t)return;const i=t.selected,s=t.parent;s&&(s.removeChild(t),s.setExpandable(s.childCount()>0),i&&s.select()),this.sharedStorageTreeElements.delete(e.securityOrigin)}sharedStorageAccess(e){this.sharedStorageListTreeElement.addEvent(e.data)}selectDatabase(e){if(e){this.showDatabase(e);const t=this.databaseTreeElements.get(e);t&&t.select()}}async showResource(e,t,i){await this.resourcesSection.revealResource(e,t,i)}showFrame(e){this.resourcesSection.revealAndSelectFrame(e)}showDatabase(e,t){if(!e)return;let i;if(t){let s=this.databaseTableViews.get(e);s||(s={},this.databaseTableViews.set(e,s)),i=s[t],i||(i=new it(e,t),s[t]=i)}else i=this.databaseQueryViews.get(e),i||(i=new $e(e),this.databaseQueryViews.set(e,i),i.addEventListener(Je.SchemaUpdated,(e=>{this.updateDatabaseTables(e)}),this));this.innerShowView(i)}showFileSystem(e){this.innerShowView(e)}innerShowView(e){this.panel.showView(e)}async updateDatabaseTables(e){const t=e.data;if(!t)return;const i=this.databaseTreeElements.get(t);if(!i)return;i.invalidateChildren();const s=this.databaseTableViews.get(t);if(!s)return;const r=new Set,a=this.panel,o=await t.tableNames();for(const e of o)r.add(e);for(const e in s)r.has(e)||(a.visibleView===s[e]&&a.showView(null),delete s[e]);await i.updateChildren()}onmousemove(e){const t=e.target;if(!t)return;const i=l.UIUtils.enclosingNodeOrSelfWithNodeName(t,"li");if(!i)return;const s=l.TreeOutline.TreeElement.getTreeElementBylistItemNode(i);this.previousHoveredElement!==s&&(this.previousHoveredElement&&(this.previousHoveredElement.hovered=!1,delete this.previousHoveredElement),s instanceof Rs&&(this.previousHoveredElement=s,s.hovered=!0))}onmouseleave(e){this.previousHoveredElement&&(this.previousHoveredElement.hovered=!1,delete this.previousHoveredElement)}wasShown(){super.wasShown(),this.sidebarTree.registerCSSFiles([Ce])}}class ps extends D{serviceName;view;model;selectedInternal;constructor(e,t){super(e,X.getUIString(t),!1),this.serviceName=t,this.selectedInternal=!1,this.view=null,this.model=null;const i=l.Icon.Icon.create(this.getIconType(),"resource-tree-item");this.setLeadingIcons([i])}getIconType(){switch(this.serviceName){case"backgroundFetch":return"arrow-up-down";case"backgroundSync":return"sync";case"pushMessaging":return"cloud";case"notifications":return"bell";case"paymentHandler":return"credit-card";case"periodicBackgroundSync":return"watch";default:return console.error(`Service ${this.serviceName} does not have a dedicated icon`),"table"}}initialize(e){this.model=e,this.selectedInternal&&!this.view&&this.onselect(!1)}get itemURL(){return`background-service://${this.serviceName}`}get selectable(){return!!this.model&&super.selectable}onselect(e){return super.onselect(e),this.selectedInternal=!0,!!this.model&&(this.view||(this.view=new X(this.serviceName,this.model)),this.showView(this.view),l.Context.Context.instance().setFlavor(X,this.view),t.userMetrics.panelShown("background_service_"+this.serviceName),!1)}}class ms extends D{sidebar;database;constructor(e,t){super(e.panel,t.name,!0),this.sidebar=e,this.database=t;const i=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([i])}get itemURL(){return"database://"+encodeURI(this.database.name)}onselect(e){return super.onselect(e),this.sidebar.showDatabase(this.database),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.web_sql]),!1}onexpand(){this.updateChildren()}async updateChildren(){this.removeChildren();const e=await this.database.tableNames();for(const t of e)this.appendChild(new ws(this.sidebar,this.database,t))}}class ws extends D{sidebar;database;tableName;constructor(e,t,i){super(e.panel,i,!1),this.sidebar=e,this.database=t,this.tableName=i;const s=l.Icon.Icon.create("table","resource-tree-item");this.setLeadingIcons([s])}get itemURL(){return"database://"+encodeURI(this.database.name)+"/"+encodeURI(this.tableName)}onselect(e){return super.onselect(e),this.sidebar.showDatabase(this.database,this.tableName),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.web_sql]),!1}}class vs extends D{view;constructor(e){super(e,i.i18n.lockedString("Service Workers"),!1);const t=l.Icon.Icon.create("gears","resource-tree-item");this.setLeadingIcons([t])}get itemURL(){return"service-workers://"}onselect(e){return super.onselect(e),this.view||(this.view=new ri),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.service_workers]),!1}}class Ss extends D{view;constructor(t){super(t,cs(ds.manifest),!0);const i=l.Icon.Icon.create("document","resource-tree-item");this.setLeadingIcons([i]),self.onInvokeElement(this.listItemElement,this.onInvoke.bind(this));const s=new l.EmptyWidget.EmptyWidget(cs(ds.noManifestDetected)),r=new l.ReportView.ReportView(cs(ds.appManifest));this.view=new O(s,r,new e.Throttler.Throttler(1e3)),l.ARIAUtils.setLabel(this.listItemElement,cs(ds.onInvokeManifestAlert));this.view.contentElement.addEventListener("manifestDetection",(e=>{this.setExpandable(e.detail)}))}get itemURL(){return"manifest://"}onselect(e){return super.onselect(e),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.app_manifest]),!1}generateChildren(){const e=this.view.getStaticSections();for(const t of e){const e=t.getTitleElement(),i=t.title(),s=t.getFieldElement(),r=new bs(this.resourcesPanel,e,i,s);this.appendChild(r)}}onInvoke(){this.view.getManifestElement().scrollIntoView(),l.ARIAUtils.alert(cs(ds.onInvokeAlert,{PH1:this.listItemElement.title}))}showManifestView(){this.showView(this.view)}}class bs extends D{#x;#R;constructor(e,t,i,s){super(e,i,!1);const r=l.Icon.Icon.create("document","resource-tree-item");this.setLeadingIcons([r]),this.#x=t,this.#R=s,self.onInvokeElement(this.listItemElement,this.onInvoke.bind(this)),this.listItemElement.addEventListener("keydown",this.onInvokeElementKeydown.bind(this)),l.ARIAUtils.setLabel(this.listItemElement,cs(ds.beforeInvokeAlert,{PH1:this.listItemElement.title}))}get itemURL(){return"manifest://"+this.title}onInvoke(){this.parent?.showManifestView(),this.#x.scrollIntoView(),l.ARIAUtils.alert(cs(ds.onInvokeAlert,{PH1:this.listItemElement.title})),t.userMetrics.manifestSectionSelected(this.listItemElement.title)}onInvokeElementKeydown(e){if("Tab"!==e.key||e.shiftKey)return;const t=this.#R.querySelector(".mask-checkbox");let i=this.#R.querySelector('[tabindex="0"]');t&&t.shadowRoot?i=t.shadowRoot.querySelector("input")||null:i||(i=this.#R.querySelector("devtools-protocol-handlers-view")?.shadowRoot?.querySelector('[tabindex="0"]')||null),i&&(i?.focus(),e.consume(!0))}}class ys extends D{view;constructor(e){super(e,cs(ds.storage),!1);const t=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([t])}get itemURL(){return"clear-storage://"}onselect(e){return super.onselect(e),this.view||(this.view=new Ui),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.storage]),!1}}class ks extends P{idbDatabaseTreeElements;constructor(e){super(e,cs(ds.indexeddb),"IndexedDB");const t=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([t]),this.idbDatabaseTreeElements=[],this.initialize()}initialize(){o.TargetManager.TargetManager.instance().addModelListener(lt,ct.DatabaseAdded,this.indexedDBAdded,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(lt,ct.DatabaseRemoved,this.indexedDBRemoved,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(lt,ct.DatabaseLoaded,this.indexedDBLoaded,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(lt,ct.IndexedDBContentUpdated,this.indexedDBContentUpdated,this,{scoped:!0}),this.idbDatabaseTreeElements=[];for(const e of o.TargetManager.TargetManager.instance().models(lt,{scoped:!0})){const t=e.databases();for(let i=0;i<t.length;++i)this.addIndexedDB(e,t[i])}}removeIndexedDBForModel(e){const t=this.idbDatabaseTreeElements.filter((t=>t.model===e));for(const e of t)this.removeIDBDatabaseTreeElement(e)}onattach(){super.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.defaultSection().appendItem(cs(ds.refreshIndexeddb),this.refreshIndexedDB.bind(this)),t.show()}refreshIndexedDB(){for(const e of o.TargetManager.TargetManager.instance().models(lt,{scoped:!0}))e.refreshDatabaseNames()}indexedDBAdded({data:{databaseId:e,model:t}}){this.addIndexedDB(t,e)}addIndexedDB(e,t){const i=new fs(this.resourcesPanel,e,t);this.idbDatabaseTreeElements.push(i),this.appendChild(i),e.refreshDatabase(t)}indexedDBRemoved({data:{databaseId:e,model:t}}){const i=this.idbDatabaseTreeElement(t,e);i&&this.removeIDBDatabaseTreeElement(i)}removeIDBDatabaseTreeElement(e){e.clear(),this.removeChild(e),s.ArrayUtilities.removeElement(this.idbDatabaseTreeElements,e),this.setExpandable(this.childCount()>0)}indexedDBLoaded({data:{database:e,model:t,entriesUpdated:i}}){const s=this.idbDatabaseTreeElement(t,e.databaseId);s&&(s.update(e,i),this.indexedDBLoadedForTest())}indexedDBLoadedForTest(){}indexedDBContentUpdated({data:{databaseId:e,objectStoreName:t,model:i}}){const s=this.idbDatabaseTreeElement(i,e);s&&s.indexedDBContentUpdated(t)}idbDatabaseTreeElement(e,t){return this.idbDatabaseTreeElements.find((i=>i.databaseId.equals(t)&&i.model===e))||null}}class fs extends D{model;databaseId;idbObjectStoreTreeElements;database;view;constructor(e,t,i){super(e,i.name,!1),this.model=t,this.databaseId=i,this.idbObjectStoreTreeElements=new Map;const s=l.Icon.Icon.create("database","resource-tree-item");this.setLeadingIcons([s]),this.model.addEventListener(ct.DatabaseNamesRefreshed,this.refreshIndexedDB,this)}get itemURL(){return"indexedDB://"+this.databaseId.storageBucket.storageKey+"/"+(this.databaseId.storageBucket.name??"")+"/"+this.databaseId.name}onattach(){super.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.defaultSection().appendItem(cs(ds.refreshIndexeddb),this.refreshIndexedDB.bind(this)),t.show()}refreshIndexedDB(){this.model.refreshDatabase(this.databaseId)}indexedDBContentUpdated(e){const t=this.idbObjectStoreTreeElements.get(e);t&&t.markNeedsRefresh()}update(e,t){this.database=e;const i=new Set;for(const e of[...this.database.objectStores.keys()].sort()){const s=this.database.objectStores.get(e);if(!s)continue;i.add(s.name);let r=this.idbObjectStoreTreeElements.get(s.name);r||(r=new Cs(this.resourcesPanel,this.model,this.databaseId,s),this.idbObjectStoreTreeElements.set(s.name,r),this.appendChild(r)),r.update(s,t)}for(const e of this.idbObjectStoreTreeElements.keys())i.has(e)||this.objectStoreRemoved(e);this.view&&this.view.getComponent().update(e),this.updateTooltip()}updateTooltip(){const e=this.database?this.database.version:"-";0===Object.keys(this.idbObjectStoreTreeElements).length?this.tooltip=cs(ds.versionSEmpty,{PH1:e}):this.tooltip=cs(ds.versionS,{PH1:e})}get selectable(){return!!this.database&&super.selectable}onselect(e){return super.onselect(e),!!this.database&&(this.view||(this.view=n.LegacyWrapper.legacyWrapper(l.Widget.VBox,new kt(this.model,this.database))),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.indexed_db]),!1)}objectStoreRemoved(e){const t=this.idbObjectStoreTreeElements.get(e);t&&(t.clear(),this.removeChild(t)),this.idbObjectStoreTreeElements.delete(e),this.updateTooltip()}clear(){for(const e of this.idbObjectStoreTreeElements.keys())this.objectStoreRemoved(e)}}class Cs extends D{model;databaseId;idbIndexTreeElements;objectStore;view;constructor(e,t,i,s){super(e,s.name,!1),this.model=t,this.databaseId=i,this.idbIndexTreeElements=new Map,this.objectStore=s,this.view=null;const r=l.Icon.Icon.create("table","resource-tree-item");this.setLeadingIcons([r])}get itemURL(){return"indexedDB://"+this.databaseId.storageBucket.storageKey+"/"+(this.databaseId.storageBucket.name??"")+"/"+this.databaseId.name+"/"+this.objectStore.name}onattach(){super.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}markNeedsRefresh(){this.view&&this.view.markNeedsRefresh();for(const e of this.idbIndexTreeElements.values())e.markNeedsRefresh()}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.defaultSection().appendItem(cs(ds.clear),this.clearObjectStore.bind(this)),t.show()}refreshObjectStore(){this.view&&this.view.refreshData();for(const e of this.idbIndexTreeElements.values())e.refreshIndex()}async clearObjectStore(){await this.model.clearObjectStore(this.databaseId,this.objectStore.name),this.update(this.objectStore,!0)}update(e,t){this.objectStore=e;const i=new Set;for(const e of this.objectStore.indexes.values()){i.add(e.name);let s=this.idbIndexTreeElements.get(e.name);s||(s=new Ts(this.resourcesPanel,this.model,this.databaseId,this.objectStore,e,this.refreshObjectStore.bind(this)),this.idbIndexTreeElements.set(e.name,s),this.appendChild(s)),s.update(this.objectStore,e,t)}for(const e of this.idbIndexTreeElements.keys())i.has(e)||this.indexRemoved(e);for(const[e,t]of this.idbIndexTreeElements.entries())i.has(e)||(this.removeChild(t),this.idbIndexTreeElements.delete(e));this.childCount()&&this.expand(),this.view&&t&&this.view.update(this.objectStore,null),this.updateTooltip()}updateTooltip(){const e=this.objectStore.keyPathString;let t=null!==e?cs(ds.keyPathS,{PH1:e}):"";this.objectStore.autoIncrement&&(t+="\n"+i.i18n.lockedString("autoIncrement")),this.tooltip=t}onselect(e){return super.onselect(e),this.view||(this.view=new ft(this.model,this.databaseId,this.objectStore,null,this.refreshObjectStore.bind(this))),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.indexed_db]),!1}indexRemoved(e){const t=this.idbIndexTreeElements.get(e);t&&(t.clear(),this.removeChild(t)),this.idbIndexTreeElements.delete(e)}clear(){for(const e of this.idbIndexTreeElements.keys())this.indexRemoved(e);this.view&&this.view.clear()}}class Ts extends D{model;databaseId;objectStore;index;refreshObjectStore;view;constructor(e,t,i,s,r,a){super(e,r.name,!1),this.model=t,this.databaseId=i,this.objectStore=s,this.index=r,this.refreshObjectStore=a}get itemURL(){return"indexedDB://"+this.databaseId.storageBucket.storageKey+"/"+(this.databaseId.storageBucket.name??"")+"/"+this.databaseId.name+"/"+this.objectStore.name+"/"+this.index.name}markNeedsRefresh(){this.view&&this.view.markNeedsRefresh()}refreshIndex(){this.view&&this.view.refreshData()}update(e,t,i){this.objectStore=e,this.index=t,this.view&&i&&this.view.update(this.objectStore,this.index),this.updateTooltip()}updateTooltip(){const e=[],t=this.index.keyPathString;e.push(cs(ds.keyPathS,{PH1:t})),this.index.unique&&e.push(i.i18n.lockedString("unique")),this.index.multiEntry&&e.push(i.i18n.lockedString("multiEntry")),this.tooltip=e.join("\n")}onselect(e){return super.onselect(e),this.view||(this.view=new ft(this.model,this.databaseId,this.objectStore,this.index,this.refreshObjectStore)),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.indexed_db]),!1}clear(){this.view&&this.view.clear()}}class Is extends D{domStorage;constructor(e,t){super(e,t.storageKey?o.StorageKeyManager.parseStorageKey(t.storageKey).origin:cs(ds.localFiles),!1),this.domStorage=t;const i=l.Icon.Icon.create("table","resource-tree-item");this.setLeadingIcons([i])}get itemURL(){return"storage://"+this.domStorage.storageKey+"/"+(this.domStorage.isLocalStorage?"local":"session")}onselect(e){return super.onselect(e),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.dom_storage]),this.resourcesPanel.showDOMStorage(this.domStorage),!1}onattach(){super.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.defaultSection().appendItem(cs(ds.clear),(()=>this.domStorage.clear())),t.show()}}class Es extends D{target;cookieDomainInternal;constructor(e,t,i){super(e,i||cs(ds.localFiles),!1),this.target=t.resourceTreeModel().target(),this.cookieDomainInternal=i,this.tooltip=cs(ds.cookiesUsedByFramesFromS,{PH1:i});const s=l.Icon.Icon.create("cookie","resource-tree-item");this.setLeadingIcons([s])}get itemURL(){return"cookies://"+this.cookieDomainInternal}cookieDomain(){return this.cookieDomainInternal}onattach(){super.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.defaultSection().appendItem(cs(ds.clear),(()=>this.resourcesPanel.clearCookies(this.target,this.cookieDomainInternal))),t.show()}onselect(e){return super.onselect(e),this.resourcesPanel.showCookies(this.target,this.cookieDomainInternal),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.cookies]),!1}}class Ms extends l.Widget.VBox{emptyWidget;linkElement;constructor(){super(),this.element.classList.add("storage-view"),this.emptyWidget=new l.EmptyWidget.EmptyWidget(""),this.linkElement=null,this.emptyWidget.show(this.element)}setText(e){this.emptyWidget.text=e}setLink(e){e&&!this.linkElement&&(this.linkElement=this.emptyWidget.appendLink(e)),!e&&this.linkElement&&this.linkElement.classList.add("hidden"),e&&this.linkElement&&(this.linkElement.setAttribute("href",e),this.linkElement.classList.remove("hidden"))}}class xs{panel;treeElement;treeElementForFrameId;treeElementForTargetId;constructor(e,t){this.panel=e,this.treeElement=t,l.ARIAUtils.setLabel(this.treeElement.listItemNode,"Resources Section"),this.treeElementForFrameId=new Map,this.treeElementForTargetId=new Map;const i=o.FrameManager.FrameManager.instance();i.addEventListener(o.FrameManager.Events.FrameAddedToTarget,(e=>this.frameAdded(e.data.frame)),this),i.addEventListener(o.FrameManager.Events.FrameRemoved,(e=>this.frameDetached(e.data.frameId)),this),i.addEventListener(o.FrameManager.Events.FrameNavigated,(e=>this.frameNavigated(e.data.frame)),this),i.addEventListener(o.FrameManager.Events.ResourceAdded,(e=>this.resourceAdded(e.data.resource)),this),o.TargetManager.TargetManager.instance().addModelListener(o.ChildTargetManager.ChildTargetManager,o.ChildTargetManager.Events.TargetCreated,this.windowOpened,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.ChildTargetManager.ChildTargetManager,o.ChildTargetManager.Events.TargetInfoChanged,this.windowChanged,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.ChildTargetManager.ChildTargetManager,o.ChildTargetManager.Events.TargetDestroyed,this.windowDestroyed,this,{scoped:!0}),o.TargetManager.TargetManager.instance().observeTargets(this,{scoped:!0})}initialize(){const e=o.FrameManager.FrameManager.instance();for(const t of e.getAllFrames()){this.treeElementForFrameId.get(t.id)||this.addFrameAndParents(t);const e=t.resourceTreeModel().target().model(o.ChildTargetManager.ChildTargetManager);if(e)for(const t of e.targetInfos())this.windowOpened({data:t})}}targetAdded(e){e.type()!==o.Target.Type.Worker&&e.type()!==o.Target.Type.ServiceWorker||this.workerAdded(e),e.type()===o.Target.Type.Frame&&e===e.outermostTarget()&&this.initialize()}async workerAdded(e){const t=e.parentTarget();if(!t)return;const i=t.id(),s=this.treeElementForTargetId.get(i),r=e.id();hs(r);const{targetInfo:a}=await t.targetAgent().invoke_getTargetInfo({targetId:r});s&&a&&s.workerCreated(a)}targetRemoved(e){}addFrameAndParents(e){const t=e.parentFrame();t&&!this.treeElementForFrameId.get(t.id)&&this.addFrameAndParents(t),this.frameAdded(e)}expandFrame(e){if(!e)return!1;let t=this.treeElementForFrameId.get(e.id);return!(!t&&!this.expandFrame(e.parentFrame()))&&(t=this.treeElementForFrameId.get(e.id),!!t&&(t.expand(),!0))}async revealResource(e,t,i){if(!this.expandFrame(e.frame()))return;const s=Ds.forResource(e);s&&await s.revealResource(t,i)}revealAndSelectFrame(e){const t=this.treeElementForFrameId.get(e.id);t?.reveal(),t?.select()}frameAdded(e){if(!o.TargetManager.TargetManager.instance().isInScope(e.resourceTreeModel()))return;const t=e.parentFrame(),i=t?this.treeElementForFrameId.get(t.id):this.treeElement;if(!i)return;const s=this.treeElementForFrameId.get(e.id);s&&(this.treeElementForFrameId.delete(e.id),s.parent&&s.parent.removeChild(s));const r=new Rs(this,e);this.treeElementForFrameId.set(e.id,r);const a=e.resourceTreeModel().target().id();this.treeElementForTargetId.get(a)||this.treeElementForTargetId.set(a,r),i.appendChild(r);for(const t of e.resources())this.resourceAdded(t)}frameDetached(e){const t=this.treeElementForFrameId.get(e);t&&(this.treeElementForFrameId.delete(e),t.parent&&t.parent.removeChild(t))}frameNavigated(e){if(!o.TargetManager.TargetManager.instance().isInScope(e.resourceTreeModel()))return;const t=this.treeElementForFrameId.get(e.id);t&&t.frameNavigated(e)}resourceAdded(e){const t=e.frame();if(!t)return;if(!o.TargetManager.TargetManager.instance().isInScope(t.resourceTreeModel()))return;const i=this.treeElementForFrameId.get(t.id);i&&i.appendResource(e)}windowOpened(e){const t=e.data;if(t.openerId&&"page"===t.type){const e=this.treeElementForFrameId.get(t.openerId);e&&(this.treeElementForTargetId.set(t.targetId,e),e.windowOpened(t))}}windowDestroyed(e){const t=e.data,i=this.treeElementForTargetId.get(t);i&&(i.windowDestroyed(t),this.treeElementForTargetId.delete(t))}windowChanged(e){const t=e.data;if(t.openerId&&"page"===t.type){const e=this.treeElementForFrameId.get(t.openerId);e&&e.windowChanged(t)}}reset(){this.treeElement.removeChildren(),this.treeElementForFrameId.clear(),this.treeElementForTargetId.clear()}}class Rs extends D{section;frame;frameId;categoryElements;treeElementForResource;treeElementForWindow;treeElementForWorker;view;constructor(e,t){super(e.panel,"",!1),this.section=e,this.frame=t,this.frameId=t.id,this.categoryElements=new Map,this.treeElementForResource=new Map,this.treeElementForWindow=new Map,this.treeElementForWorker=new Map,this.frameNavigated(t),this.view=null}getIconTypeForFrame(e){return e.isOutermostFrame()?e.unreachableUrl()?"frame-crossed":"frame":e.unreachableUrl()?"iframe-crossed":"iframe"}async frameNavigated(e){const t=l.Icon.Icon.create(this.getIconTypeForFrame(e));if(e.unreachableUrl()&&t.classList.add("red-icon"),this.setLeadingIcons([t]),this.invalidateChildren(),this.frameId=e.id,this.title!==e.displayName()&&(this.title=e.displayName(),l.ARIAUtils.setLabel(this.listItemElement,this.title),this.parent)){const e=this.parent;e.removeChild(this),e.appendChild(this)}if(this.categoryElements.clear(),this.treeElementForResource.clear(),this.treeElementForWorker.clear(),this.selected?(this.view=n.LegacyWrapper.legacyWrapper(l.Widget.Widget,new u.FrameDetailsView.FrameDetailsReportView(this.frame)),this.showView(this.view)):this.view=null,e.isOutermostFrame()){const t=o.TargetManager.TargetManager.instance().targets();for(const i of t)if(i.type()===o.Target.Type.ServiceWorker&&o.TargetManager.TargetManager.instance().isInScope(i)){const t=i.id();hs(t);const s=e.resourceTreeModel().target().targetAgent(),r=(await s.invoke_getTargetInfo({targetId:t})).targetInfo;this.workerCreated(r)}}}get itemURL(){return this.frame.isOutermostFrame()?"frame://":"frame://"+encodeURI(this.frame.url)}onselect(e){return super.onselect(e),this.view||(this.view=n.LegacyWrapper.legacyWrapper(l.Widget.Widget,new u.FrameDetailsView.FrameDetailsReportView(this.frame))),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.frame_details]),this.showView(this.view),this.listItemElement.classList.remove("hovered"),o.OverlayModel.OverlayModel.hideDOMNodeHighlight(),!1}set hovered(e){e?(this.listItemElement.classList.add("hovered"),this.frame.highlight()):(this.listItemElement.classList.remove("hovered"),o.OverlayModel.OverlayModel.hideDOMNodeHighlight())}appendResource(t){const i=t.statusCode();if(i>=301&&i<=303)return;const s=t.resourceType(),r=s.name();let a=s===e.ResourceType.resourceTypes.Document?this:this.categoryElements.get(r);a||(a=new P(this.section.panel,t.resourceType().category().title(),r,"Frames"===r),this.categoryElements.set(s.name(),a),this.appendChild(a,Rs.presentationOrderCompare));const o=new Ds(this.section.panel,t);a.appendChild(o,Rs.presentationOrderCompare),this.treeElementForResource.set(t.url,o)}windowOpened(e){const t="OpenedWindows";let i=this.categoryElements.get(t);if(i||(i=new P(this.section.panel,cs(ds.openedWindows),t),this.categoryElements.set(t,i),this.appendChild(i,Rs.presentationOrderCompare)),!this.treeElementForWindow.get(e.targetId)){const t=new Ps(this.section.panel,e);i.appendChild(t),this.treeElementForWindow.set(e.targetId,t)}}workerCreated(e){const t="service_worker"===e.type?"Service Workers":"Web Workers",s="service_worker"===e.type?i.i18n.lockedString("Service Workers"):cs(ds.webWorkers);let r=this.categoryElements.get(t);if(r||(r=new P(this.section.panel,s,t),this.categoryElements.set(t,r),this.appendChild(r,Rs.presentationOrderCompare)),!this.treeElementForWorker.get(e.targetId)){const t=new Bs(this.section.panel,e);r.appendChild(t),this.treeElementForWorker.set(e.targetId,t)}}windowChanged(e){const t=this.treeElementForWindow.get(e.targetId);t&&(t.title!==e.title&&(t.title=e.title),t.update(e))}windowDestroyed(e){const t=this.treeElementForWindow.get(e);t&&t.windowClosed()}appendChild(e,t=Rs.presentationOrderCompare){super.appendChild(e,t)}static presentationOrderCompare(e,t){function i(e){return e instanceof P?2:e instanceof Rs?1:3}return i(e)-i(t)||e.titleAsText().localeCompare(t.titleAsText())}}const Ls=new WeakMap;class Ds extends D{panel;resource;previewPromise;constructor(e,t){super(e,t.isGenerated?cs(ds.documentNotAvailable):t.displayName,!1),this.panel=e,this.resource=t,this.previewPromise=null,this.tooltip=t.url,Ls.set(this.resource,this);const i=l.Icon.Icon.create("document","navigator-file-tree-item");i.classList.add("navigator-"+t.resourceType().name()+"-tree-item"),this.setLeadingIcons([i])}static forResource(e){return Ls.get(e)}get itemURL(){return this.resource.url}preparePreview(){if(this.previewPromise)return this.previewPromise;const e=d.PreviewFactory.PreviewFactory.createPreview(this.resource,this.resource.mimeType);return this.previewPromise=e.then((e=>e||new l.EmptyWidget.EmptyWidget(this.resource.url))),this.previewPromise}onselect(e){return super.onselect(e),this.resource.isGenerated?this.panel.showCategoryView(cs(ds.theContentOfThisDocumentHasBeen),null):this.panel.scheduleShowView(this.preparePreview()),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.frame_resource]),!1}ondblclick(e){return t.InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(this.resource.url),!1}onattach(){super.onattach(),this.listItemElement.draggable=!0,this.listItemElement.addEventListener("dragstart",this.ondragstart.bind(this),!1),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!0)}ondragstart(e){return!!e.dataTransfer&&(e.dataTransfer.setData("text/plain",this.resource.content||""),e.dataTransfer.effectAllowed="copy",!0)}handleContextMenuEvent(e){const t=new l.ContextMenu.ContextMenu(e);t.appendApplicableItems(this.resource),t.show()}async revealResource(e,t){this.revealAndSelect(!0);const i=await this.panel.scheduleShowView(this.preparePreview());i instanceof d.ResourceSourceFrame.ResourceSourceFrame&&"number"==typeof e&&i.revealPosition({lineNumber:e,columnNumber:t},!0)}}class Ps extends D{targetInfo;isWindowClosed;view;constructor(e,t){super(e,t.title||cs(ds.windowWithoutTitle),!1),this.targetInfo=t,this.isWindowClosed=!1,this.view=null,this.updateIcon(t.canAccessOpener)}updateIcon(e){const t=e?"popup":"frame",i=l.Icon.Icon.create(t);this.setLeadingIcons([i])}update(e){e.canAccessOpener!==this.targetInfo.canAccessOpener&&this.updateIcon(e.canAccessOpener),this.targetInfo=e,this.view&&(this.view.setTargetInfo(e),this.view.update())}windowClosed(){this.listItemElement.classList.add("window-closed"),this.isWindowClosed=!0,this.view&&(this.view.setIsWindowClosed(!0),this.view.update())}onselect(e){return super.onselect(e),this.view?this.view.update():this.view=new qt(this.targetInfo,this.isWindowClosed),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.frame_window]),!1}get itemURL(){return this.targetInfo.url}}class Bs extends D{targetInfo;view;constructor(e,t){super(e,t.title||t.url||cs(ds.worker),!1),this.targetInfo=t,this.view=null;const i=l.Icon.Icon.create("gears","navigator-file-tree-item");this.setLeadingIcons([i])}onselect(e){return super.onselect(e),this.view?this.view.update():this.view=new Kt(this.targetInfo),this.showView(this.view),t.userMetrics.panelShown(t.UserMetrics.PanelCodes[t.UserMetrics.PanelCodes.frame_worker]),!1}get itemURL(){return this.targetInfo.url}}var Fs=Object.freeze({__proto__:null,get SharedStorageTreeElementDispatcher(){return gs},ApplicationPanelSidebar:us,BackgroundServiceTreeElement:ps,DatabaseTreeElement:ms,DatabaseTableTreeElement:ws,ServiceWorkersTreeElement:vs,AppManifestTreeElement:Ss,ManifestChildTreeElement:bs,ClearStorageTreeElement:ys,IndexedDBTreeElement:ks,IDBDatabaseTreeElement:fs,IDBObjectStoreTreeElement:Cs,IDBIndexTreeElement:Ts,DOMStorageTreeElement:Is,CookieTreeElement:Es,StorageCategoryView:Ms,ResourcesSection:xs,FrameTreeElement:Rs,FrameResourceTreeElement:Ds});const Vs=new CSSStyleSheet;Vs.replaceSync(".cookie-preview-widget{padding:2px 6px}.cookie-preview-widget-header{color:var(--color-text-secondary);font-weight:bold;user-select:none;white-space:nowrap;margin-bottom:4px;flex:0 0 18px;display:flex;align-items:center}.cookie-preview-widget-header-label{line-height:18px}.cookie-preview-widget-cookie-value{user-select:text;word-break:break-all;flex:1;overflow:auto}.cookie-preview-widget-toggle{margin-left:12px;font-weight:normal}\n/*# sourceURL=cookieItemsView.css */\n");const As={showUrlDecoded:"Show URL-decoded",cookies:"Cookies",selectACookieToPreviewItsValue:"Select a cookie to preview its value",onlyShowCookiesWithAnIssue:"Only show cookies with an issue",onlyShowCookiesWhichHaveAn:"Only show cookies that have an associated issue",clearFilteredCookies:"Clear filtered cookies",clearAllCookies:"Clear all cookies",numberOfCookiesShownInTableS:"Number of cookies shown in table: {PH1}"},Os=i.i18n.registerUIStrings("panels/application/CookieItemsView.ts",As),Ws=i.i18n.getLocalizedString.bind(void 0,Os);class Us extends l.Widget.VBox{cookie;showDecodedSetting;toggle;value;constructor(){super(),this.setMinimumSize(230,45),this.cookie=null,this.showDecodedSetting=e.Settings.Settings.instance().createSetting("cookieViewShowDecoded",!1);const t=document.createElement("div");t.classList.add("cookie-preview-widget-header");const i=document.createElement("span");i.classList.add("cookie-preview-widget-header-label"),i.textContent="Cookie Value",t.appendChild(i),this.contentElement.appendChild(t);const s=l.UIUtils.CheckboxLabel.create(Ws(As.showUrlDecoded),this.showDecodedSetting.get());s.classList.add("cookie-preview-widget-toggle"),s.checkboxElement.addEventListener("click",(()=>this.showDecoded(!this.showDecodedSetting.get()))),t.appendChild(s),this.toggle=s;const r=document.createElement("div");r.classList.add("cookie-preview-widget-cookie-value"),r.textContent="",r.addEventListener("dblclick",this.handleDblClickOnCookieValue.bind(this)),this.value=r,this.contentElement.classList.add("cookie-preview-widget"),this.contentElement.appendChild(r)}showDecoded(e){this.cookie&&(this.showDecodedSetting.set(e),this.toggle.checkboxElement.checked=e,this.updatePreview())}updatePreview(){this.cookie?this.value.textContent=this.showDecodedSetting.get()?decodeURIComponent(this.cookie.value()):this.cookie.value():this.value.textContent=""}setCookie(e){this.cookie=e,this.updatePreview()}handleDblClickOnCookieValue(e){e.preventDefault();const t=document.createRange();t.selectNode(this.value);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(t))}}class Ns extends Ii{model;cookieDomain;totalSize;cookiesTable;splitWidget;previewPanel;previewWidget;emptyWidget;onlyIssuesFilterUI;refreshThrottler;eventDescriptors;allCookies;shownCookies;selectedCookie;constructor(t,i){super(Ws(As.cookies),"cookiesPanel"),this.element.classList.add("storage-view"),this.model=t,this.cookieDomain=i,this.totalSize=0,this.cookiesTable=new R.CookiesTable.CookiesTable(!1,this.saveCookie.bind(this),this.refreshItems.bind(this),this.handleCookieSelected.bind(this),this.deleteCookie.bind(this)),this.cookiesTable.setMinimumSize(0,50),this.splitWidget=new l.SplitWidget.SplitWidget(!1,!0,"cookieItemsSplitViewState"),this.splitWidget.show(this.element),this.previewPanel=new l.Widget.VBox;const s=this.previewPanel.element.createChild("div","preview-panel-resizer");this.splitWidget.setMainWidget(this.cookiesTable),this.splitWidget.setSidebarWidget(this.previewPanel),this.splitWidget.installResizer(s),this.previewWidget=new Us,this.emptyWidget=new l.EmptyWidget.EmptyWidget(Ws(As.selectACookieToPreviewItsValue)),this.emptyWidget.show(this.previewPanel.contentElement),this.onlyIssuesFilterUI=new l.Toolbar.ToolbarCheckbox(Ws(As.onlyShowCookiesWithAnIssue),Ws(As.onlyShowCookiesWhichHaveAn),(()=>{this.updateWithCookies(this.allCookies)})),this.appendToolbarItem(this.onlyIssuesFilterUI),this.refreshThrottler=new e.Throttler.Throttler(300),this.eventDescriptors=[],this.allCookies=[],this.shownCookies=[],this.selectedCookie=null,this.setCookiesDomain(t,i)}setCookiesDomain(t,i){this.model=t,this.cookieDomain=i,this.refreshItems(),e.EventTarget.removeEventListeners(this.eventDescriptors);const s=t.target().model(o.NetworkManager.NetworkManager);s&&(this.eventDescriptors=[s.addEventListener(o.NetworkManager.Events.ResponseReceived,this.onResponseReceived,this),s.addEventListener(o.NetworkManager.Events.LoadingFinished,this.onLoadingFinished,this)])}showPreview(e){e!==this.selectedCookie&&(this.selectedCookie=e,e?(this.emptyWidget.detach(),this.previewWidget.setCookie(e),this.previewWidget.show(this.previewPanel.contentElement)):(this.previewWidget.detach(),this.emptyWidget.show(this.previewPanel.contentElement)))}handleCookieSelected(){const e=this.cookiesTable.selectedCookie();this.setCanDeleteSelected(Boolean(e)),this.showPreview(e)}async saveCookie(e,t){return t&&e.key()!==t.key()&&await this.model.deleteCookie(t),this.model.saveCookie(e)}deleteCookie(e,t){this.model.deleteCookie(e).then(t)}updateWithCookies(t){this.allCookies=t,this.totalSize=t.reduce(((e,t)=>e+t.size()),0);const i=e.ParsedURL.ParsedURL.fromString(this.cookieDomain),s=i?i.host:"";this.cookiesTable.setCookieDomain(s),this.shownCookies=this.filter(t,(e=>`${e.name()} ${e.value()} ${e.domain()}`)),this.hasFilter()?(this.setDeleteAllTitle(Ws(As.clearFilteredCookies)),this.setDeleteAllGlyph("filter-clear")):(this.setDeleteAllTitle(Ws(As.clearAllCookies)),this.setDeleteAllGlyph("clear-list")),this.cookiesTable.setCookies(this.shownCookies,this.model.getCookieToBlockedReasonsMap()),l.ARIAUtils.alert(Ws(As.numberOfCookiesShownInTableS,{PH1:this.shownCookies.length})),this.setCanFilter(!0),this.setCanDeleteAll(this.shownCookies.length>0),this.setCanDeleteSelected(Boolean(this.cookiesTable.selectedCookie())),this.cookiesTable.selectedCookie()||this.showPreview(null)}filter(e,t){return super.filter(e,t).filter((e=>!this.onlyIssuesFilterUI.checked()||e instanceof o.Cookie.Cookie&&x.RelatedIssue.hasIssues(e)))}deleteAllItems(){this.showPreview(null),this.model.deleteCookies(this.shownCookies).then((()=>this.refreshItems()))}deleteSelectedItem(){const e=this.cookiesTable.selectedCookie();e&&(this.showPreview(null),this.model.deleteCookie(e).then((()=>this.refreshItems())))}refreshItems(){this.model.getCookiesForDomain(this.cookieDomain).then(this.updateWithCookies.bind(this))}refreshItemsThrottled(){this.refreshThrottler.schedule((()=>Promise.resolve(this.refreshItems())))}onResponseReceived(){this.refreshItemsThrottled()}onLoadingFinished(){this.refreshItemsThrottled()}wasShown(){super.wasShown(),this.registerCSSFiles([Vs])}}var Hs=Object.freeze({__proto__:null,CookieItemsView:Ns});const _s={domStorage:"DOM Storage",key:"Key",value:"Value",domStorageItems:"DOM Storage Items",domStorageItemsCleared:"DOM Storage Items cleared",selectAValueToPreview:"Select a value to preview",domStorageItemDeleted:"The storage item was deleted.",domStorageNumberEntries:"Number of entries shown in table: {PH1}"},Gs=i.i18n.registerUIStrings("panels/application/DOMStorageItemsView.ts",_s),qs=i.i18n.getLocalizedString.bind(void 0,Gs);class Ks extends Ii{domStorage;dataGrid;splitWidget;previewPanel;preview;previewValue;eventListeners;constructor(e){super(qs(_s.domStorage),"domStoragePanel"),this.domStorage=e,e.storageKey&&this.setStorageKey(e.storageKey),this.element.classList.add("storage-view","table");const t=[{id:"key",title:qs(_s.key),sortable:!1,editable:!0,longText:!0,weight:50},{id:"value",title:qs(_s.value),sortable:!1,editable:!0,longText:!0,weight:50}];this.dataGrid=new m.DataGrid.DataGridImpl({displayName:qs(_s.domStorageItems),columns:t,editCallback:this.editingCallback.bind(this),deleteCallback:this.deleteCallback.bind(this),refreshCallback:this.refreshItems.bind(this)}),this.dataGrid.addEventListener(m.DataGrid.Events.SelectedNode,(e=>{this.previewEntry(e.data)})),this.dataGrid.addEventListener(m.DataGrid.Events.DeselectedNode,(()=>{this.previewEntry(null)})),this.dataGrid.setStriped(!0),this.dataGrid.setName("DOMStorageItemsView"),this.splitWidget=new l.SplitWidget.SplitWidget(!1,!0,"domStorageSplitViewState"),this.splitWidget.show(this.element),this.previewPanel=new l.Widget.VBox,this.previewPanel.setMinimumSize(0,50);const i=this.previewPanel.element.createChild("div","preview-panel-resizer"),s=this.dataGrid.asWidget();s.setMinimumSize(0,50),this.splitWidget.setMainWidget(s),this.splitWidget.setSidebarWidget(this.previewPanel),this.splitWidget.installResizer(i),this.preview=null,this.previewValue=null,this.showPreview(null,null),this.eventListeners=[],this.setStorage(e)}setStorage(t){e.EventTarget.removeEventListeners(this.eventListeners),this.domStorage=t,t.storageKey&&this.setStorageKey(t.storageKey),this.eventListeners=[this.domStorage.addEventListener(at.Events.DOMStorageItemsCleared,this.domStorageItemsCleared,this),this.domStorage.addEventListener(at.Events.DOMStorageItemRemoved,this.domStorageItemRemoved,this),this.domStorage.addEventListener(at.Events.DOMStorageItemAdded,this.domStorageItemAdded,this),this.domStorage.addEventListener(at.Events.DOMStorageItemUpdated,this.domStorageItemUpdated,this)],this.refreshItems()}domStorageItemsCleared(){this.isShowing()&&this.dataGrid&&(this.dataGrid.rootNode().removeChildren(),this.dataGrid.addCreationNode(!1),l.ARIAUtils.alert(qs(_s.domStorageItemsCleared)),this.setCanDeleteSelected(!1))}domStorageItemRemoved(e){if(!this.isShowing()||!this.dataGrid)return;const t=e.data,i=this.dataGrid.rootNode(),s=i.children;for(let e=0;e<s.length;++e){const r=s[e];if(r.data.key===t.key)return i.removeChild(r),void this.setCanDeleteSelected(s.length>1)}}domStorageItemAdded(e){if(!this.isShowing()||!this.dataGrid)return;const t=e.data,i=this.dataGrid.rootNode(),s=i.children;for(let e=0;e<s.length;++e)if(s[e].data.key===t.key)return;const r=new m.DataGrid.DataGridNode({key:t.key,value:t.value},!1);i.insertChild(r,s.length-1)}domStorageItemUpdated(e){if(!this.isShowing()||!this.dataGrid)return;const t=e.data,i=this.dataGrid.rootNode().children.find((e=>e.data.key===t.key));i&&(i.data.value!==t.value&&(i.data.value=t.value,i.refresh()),i.selected&&(this.previewValue!==t.value&&this.previewEntry(i),this.setCanDeleteSelected(!0)))}showDOMStorageItems(e){const t=this.dataGrid.rootNode();let i=null;for(const e of t.children)if(e.selected){i=e.data.key;break}t.removeChildren();let s=null;const r=this.filter(e,(e=>`${e[0]} ${e[1]}`));for(const e of r){const r=e[0],a=e[1],o=new m.DataGrid.DataGridNode({key:r,value:a},!1);o.selectable=!0,t.appendChild(o),s&&r!==i||(s=o)}s&&(s.selected=!0),this.dataGrid.addCreationNode(!1),this.setCanDeleteSelected(Boolean(s)),l.ARIAUtils.alert(qs(_s.domStorageNumberEntries,{PH1:r.length}))}deleteSelectedItem(){this.dataGrid&&this.dataGrid.selectedNode&&this.deleteCallback(this.dataGrid.selectedNode)}refreshItems(){this.domStorage.getItems().then((e=>e&&this.showDOMStorageItems(e)))}deleteAllItems(){this.domStorage.clear(),this.domStorageItemsCleared()}editingCallback(e,t,i,s){const r=this.domStorage;"key"===t?("string"==typeof i&&r.removeItem(i),r.setItem(s,e.data.value||""),this.removeDupes(e)):r.setItem(e.data.key||"",s)}removeDupes(e){const t=this.dataGrid.rootNode(),i=t.children;for(let s=i.length-1;s>=0;--s){const r=i[s];r.data.key===e.data.key&&e!==r&&t.removeChild(r)}}deleteCallback(e){e&&!e.isCreationNode&&(this.domStorage&&this.domStorage.removeItem(e.data.key),l.ARIAUtils.alert(qs(_s.domStorageItemDeleted)))}showPreview(e,t){this.preview&&this.previewValue===t||(this.preview&&this.preview.detach(),e||(e=new l.EmptyWidget.EmptyWidget(qs(_s.selectAValueToPreview))),this.previewValue=t,this.preview=e,e.show(this.previewPanel.contentElement))}async previewEntry(t){const i=t&&t.data&&t.data.value;if(t&&t.data&&t.data.value){const s=`${this.domStorage.isLocalStorage?"localstorage":"sessionstorage"}://${t.key}`,r=L.StaticContentProvider.StaticContentProvider.fromString(s,e.ResourceType.resourceTypes.XHR,i),a=await d.PreviewFactory.PreviewFactory.createPreview(r,"text/plain");t.selected&&this.showPreview(a,i)}else this.showPreview(null,i)}}var js=Object.freeze({__proto__:null,DOMStorageItemsView:Ks});const zs=new CSSStyleSheet;let Qs,$s,Js;zs.replaceSync(".resources-toolbar{border-top:1px solid var(--color-details-hairline);background-color:var(--color-background-elevation-1)}.top-resources-toolbar{border-bottom:1px solid var(--color-details-hairline);background-color:var(--color-background-elevation-1)}.resources.panel .status{float:right;height:16px;margin-top:1px;margin-left:4px;line-height:1em}.storage-view{display:flex;overflow:hidden}.storage-view .data-grid:not(.inline){border:none;flex:auto}.storage-view .storage-table-error{color:var(--color-accent-red);font-size:24px;font-weight:bold;padding:10px;display:flex;align-items:center;justify-content:center}.storage-view.query{padding:2px 0;overflow-y:overlay;overflow-x:hidden}.storage-view .filter-bar{border-top:none;border-bottom:1px solid var(--color-details-hairline)}.database-query-group-messages{overflow-y:auto}.database-query-prompt-container{position:relative;padding:1px 22px 1px 24px;min-height:16px}.database-query-prompt{white-space:pre-wrap}.prompt-icon{position:absolute;display:block;left:7px;top:9px;margin-top:-7px;user-select:none}.database-user-query .prompt-icon{margin-top:-10px}.database-query-prompt-container .prompt-icon{top:6px}.database-user-query{position:relative;border-bottom:1px solid var(--color-details-hairline);padding:1px 22px 1px 24px;min-height:16px;flex-shrink:0}.database-user-query:focus-visible{background-color:var(--color-background-elevation-2)}.database-query-text{color:var(--color-primary-variant);user-select:text}.database-query-result{position:relative;padding:1px 22px;min-height:16px;margin-left:-22px;padding-right:0}.database-query-result.error{color:var(--color-syntax-1);user-select:text}.database-query-result.error .prompt-icon{margin-top:-9px}.resources-sidebar{padding:0;overflow-x:auto;background-color:var(--color-background)}\n/*# sourceURL=resourcesPanel.css */\n");class Xs extends l.Panel.PanelWithSidebar{resourcesLastSelectedItemSetting;visibleView;pendingViewPromise;categoryView;storageViews;storageViewToolbar;domStorageView;cookieView;emptyWidget;sidebar;constructor(){super("resources"),this.resourcesLastSelectedItemSetting=e.Settings.Settings.instance().createSetting("resourcesLastSelectedElementPath",[]),this.visibleView=null,this.pendingViewPromise=null,this.categoryView=null;const t=new l.Widget.VBox;this.storageViews=t.element.createChild("div","vbox flex-auto"),this.storageViewToolbar=new l.Toolbar.Toolbar("resources-toolbar",t.element),this.splitWidget().setMainWidget(t),this.domStorageView=null,this.cookieView=null,this.emptyWidget=null,this.sidebar=new us(this),this.sidebar.show(this.panelSidebarElement())}static instance(e={forceNew:null}){const{forceNew:t}=e;return Qs&&!t||(Qs=new Xs),Qs}static shouldCloseOnReset(e){return[d.ResourceSourceFrame.ResourceSourceFrame,d.ImageView.ImageView,d.FontView.FontView,Ii,$e,it].some((t=>e instanceof t))}static async showAndGetSidebar(){return await l.ViewManager.ViewManager.instance().showView("resources"),Xs.instance().sidebar}focus(){this.sidebar.focus()}lastSelectedItemPath(){return this.resourcesLastSelectedItemSetting.get()}setLastSelectedItemPath(e){this.resourcesLastSelectedItemSetting.set(e)}resetView(){this.visibleView&&Xs.shouldCloseOnReset(this.visibleView)&&this.showView(null)}showView(e){this.pendingViewPromise=null,this.visibleView!==e&&(this.visibleView&&this.visibleView.detach(),e&&e.show(this.storageViews),this.visibleView=e,this.storageViewToolbar.removeToolbarItems(),this.storageViewToolbar.element.classList.toggle("hidden",!0),e instanceof l.View.SimpleView&&e.toolbarItems().then((e=>{e.map((e=>this.storageViewToolbar.appendToolbarItem(e))),this.storageViewToolbar.element.classList.toggle("hidden",!e.length)})))}async scheduleShowView(e){this.pendingViewPromise=e;const t=await e;return this.pendingViewPromise!==e?null:(this.showView(t),t)}showCategoryView(e,t){this.categoryView||(this.categoryView=new Ms),this.categoryView.setText(e),this.categoryView.setLink(t),this.showView(this.categoryView)}showDOMStorage(e){e&&(this.domStorageView?this.domStorageView.setStorage(e):this.domStorageView=new Ks(e),this.showView(this.domStorageView))}showCookies(e,t){const i=e.model(o.CookieModel.CookieModel);i&&(this.cookieView?this.cookieView.setCookiesDomain(i,t):this.cookieView=new Ns(i,t),this.showView(this.cookieView))}clearCookies(e,t){const i=e.model(o.CookieModel.CookieModel);i&&i.clear(t).then((()=>{this.cookieView&&this.cookieView.refreshItems()}))}wasShown(){super.wasShown(),this.registerCSSFiles([zs])}}class Ys{static instance(e={forceNew:null}){const{forceNew:t}=e;return $s&&!t||($s=new Ys),$s}async reveal(e){if(!(e instanceof o.Resource.Resource))throw new Error("Internal error: not a resource");const t=await Xs.showAndGetSidebar();await t.showResource(e)}}class Zs{static instance(e={forceNew:null}){const{forceNew:t}=e;return Js&&!t||(Js=new Zs),Js}async reveal(e){if(!(e instanceof o.ResourceTreeModel.ResourceTreeFrame))throw new Error("Internal error: not a frame");(await Xs.showAndGetSidebar()).showFrame(e)}}var er=Object.freeze({__proto__:null,ResourcesPanel:Xs,ResourceRevealer:Ys,FrameDetailsRevealer:Zs});export{W as AppManifestView,Fs as ApplicationPanelSidebar,K as BackgroundServiceModel,te as BackgroundServiceView,ne as BounceTrackingMitigationsTreeElement,Hs as CookieItemsView,js as DOMStorageItemsView,dt as DOMStorageModel,Ke as DatabaseModel,Ye as DatabaseQueryView,rt as DatabaseTableView,wt as IndexedDBModel,It as IndexedDBViews,Mt as InterestGroupStorageModel,Bt as InterestGroupStorageView,Wt as InterestGroupTreeElement,jt as OpenedWindowDetailsView,fe as PreloadingTreeElement,ve as PreloadingView,ts as ReportingApiReportsView,ss as ReportingApiView,er as ResourcesPanel,Pe as ServiceWorkerCacheViews,Zt as ServiceWorkerUpdateCycleView,oi as ServiceWorkersView,gi as SharedStorageEventsView,Pi as SharedStorageItemsView,Si as SharedStorageListTreeElement,ki as SharedStorageModel,Fi as SharedStorageTreeElement,Ei as StorageItemsView,Gi as StorageView,$i as TrustTokensTreeElement};
